vue 中directive功能的簡(jiǎn)單實(shí)現(xiàn)
2018年首個(gè)計(jì)劃是學(xué)習(xí)vue源碼,查閱了一番資料之后,決定從第一個(gè)commit開(kāi)始看起,這將是一場(chǎng)持久戰(zhàn)!本篇介紹directive的簡(jiǎn)單實(shí)現(xiàn),主要學(xué)習(xí)其實(shí)現(xiàn)的思路及代碼的設(shè)計(jì)(directive和filter擴(kuò)展起來(lái)非常方便,符合設(shè)計(jì)模式中的 開(kāi)閉原則 )。
構(gòu)思API
<div id="app" sd-on-click="toggle | .button"> <p sd-text="msg | capitalize"></p> <p sd-class-red="error" sd-text="content"></p> <button class="button">Toggle class</button> </div> var app = Seed.create({ id: 'app', scope: { msg: 'hello', content: 'world', error: true, toggle: function() { app.scope.error = !app.scope.error; } } });
實(shí)現(xiàn)功能夠簡(jiǎn)單吧--將scope中的數(shù)據(jù)綁定到app中。
核心邏輯設(shè)計(jì)
指令格式
以 sd-text="msg | capitalize" 為例說(shuō)明:
- sd 為統(tǒng)一的前綴標(biāo)識(shí)
- text 為指令名稱
- capitalize 為過(guò)濾器名稱
其中 | 后面為過(guò)濾器,可以添加多個(gè)。 sd-class-red
中的red為參數(shù)。
代碼結(jié)構(gòu)介紹
main.js 入口文件
// Seed構(gòu)造函數(shù) const Seed = function(opts) { }; // 對(duì)外暴露的API module.exports = { create: function(opts) { return new Seed(opts); } }; directives.js module.exports = { text: function(el, value) { el.textContent = value || ''; } }; filters.js module.exports = { capitalize: function(value) { value = value.toString(); return value.charAt(0).toUpperCase() + value.slice(1); } };
就這三個(gè)文件,其中directives和filters都是配置文件,很易于擴(kuò)展。
實(shí)現(xiàn)的大致思路如下:
1.在Seed實(shí)例創(chuàng)建的時(shí)候會(huì)依次解析el容器中node節(jié)點(diǎn)的指令
2.將指令解析結(jié)果封裝為指令對(duì)象,結(jié)構(gòu)為:
屬性 | 說(shuō)明 | 類型 |
---|---|---|
attr | 原始屬性,如 sd-text |
String |
key | 對(duì)應(yīng)scope對(duì)象中的屬性名稱 | String |
filters | 過(guò)濾器名稱列表 | Array |
definition | 該指令的定義,如text對(duì)應(yīng)的函數(shù) | Function |
argument | 從attr中解析出來(lái)的參數(shù)(只支持一個(gè)參數(shù)) | String |
update | 更新directive時(shí)調(diào)用 typeof def === 'function' ? def : def.update |
Function |
bind | 如果directive中定義了bind方法,則在 bindDirective 中會(huì)調(diào)用 |
Function |
el | 存儲(chǔ)當(dāng)前element元素 | Element |
3.想辦法執(zhí)行指令的update方法即可,該插件使用了 Object.defineProperty 來(lái)定義scope中的每個(gè)屬性,在其setter中觸發(fā)指令的update方法。
核心代碼
const prefix = 'sd'; const Directives = require('./directives'); const Filters = require('./filters'); // 結(jié)果為[sd-text], [sd-class], [sd-on]的字符串 const selector = Object.keys(Directives).map((name) => `[${prefix}-${name}]`).join(','); const Seed = function(opts) { const self = this, root = this.el = document.getElementById(opts.id), // 篩選出el下所能支持的directive的nodes列表 els = this.el.querySelectorAll(selector), bindings = {}; this.scope = {}; // 解析節(jié)點(diǎn) [].forEach.call(els, processNode); // 解析根節(jié)點(diǎn) processNode(root); // 給scope賦值,觸發(fā)setter方法,此時(shí)會(huì)調(diào)用與其相對(duì)應(yīng)的directive的update方法 Object.keys(bindings).forEach((key) => { this.scope[key] = opts.scope[key]; }); function processNode(el) { cloneAttributes(el.attributes).forEach((attr) => { const directive = parseDirective(attr); if (directive) { bindDirective(self, el, bindings, directive); } }); } };
可以看到核心方法 processNode 主要做了兩件事一個(gè)是 parseDirective ,另一個(gè)是 bindDirective 。
先來(lái)看看 parseDirective 方法:
function parseDirective(attr) { if (attr.name.indexOf(prefix) == -1) return; // 解析屬性名稱獲取directive const noprefix = attr.name.slice(prefix.length + 1), argIndex = noprefix.indexOf('-'), dirname = argIndex === -1 ? noprefix : noprefix.slice(0, argIndex), arg = argIndex === -1 ? null : noprefix.slice(argIndex + 1), def = Directives[dirname] // 解析屬性值獲取filters const exp = attr.value, pipeIndex = exp.indexOf('|'), key = (pipeIndex === -1 ? exp : exp.slice(0, pipeIndex)).trim(), filters = pipeIndex === -1 ? null : exp.slice(pipeIndex + 1).split('|').map((filterName) => filterName.trim()); return def ? { attr: attr, key: key, filters: filters, argument: arg, definition: Directives[dirname], update: typeof def === 'function' ? def : def.update } : null; }
以 sd-on-click="toggle | .button" 為例來(lái)說(shuō)明,其中attr對(duì)象的name為 sd-on-click ,value為 toggle | .button ,最終解析結(jié)果為:
{ "attr": attr, "key": "toggle", "filters": [".button"], "argument": "click", "definition": {"on": {}}, "update": function(){} }
緊接著調(diào)用 bindDirective 方法
/** * 數(shù)據(jù)綁定 * @param {Seed} seed Seed實(shí)例對(duì)象 * @param {Element} el 當(dāng)前node節(jié)點(diǎn) * @param {Object} bindings 數(shù)據(jù)綁定存儲(chǔ)對(duì)象 * @param {Object} directive 指令解析結(jié)果 */ function bindDirective(seed, el, bindings, directive) { // 移除指令屬性 el.removeAttribute(directive.attr.name); // 數(shù)據(jù)屬性 const key = directive.key; let binding = bindings[key]; if (!binding) { bindings[key] = binding = { value: undefined, directives: [] // 與該數(shù)據(jù)相關(guān)的指令 }; } directive.el = el; binding.directives.push(directive); if (!seed.scope.hasOwnProperty(key)) { bindAccessors(seed, key, binding); } } /** * 重寫(xiě)scope西鄉(xiāng)屬性的getter和setter * @param {Seed} seed Seed實(shí)例 * @param {String} key 對(duì)象屬性即opts.scope中的屬性 * @param {Object} binding 數(shù)據(jù)綁定關(guān)系對(duì)象 */ function bindAccessors(seed, key, binding) { Object.defineProperty(seed.scope, key, { get: function() { return binding.value; }, set: function(value) { binding.value = value; // 觸發(fā)directive binding.directives.forEach((directive) => { // 如果有過(guò)濾器則先執(zhí)行過(guò)濾器 if (typeof value !== 'undefined' && directive.filters) { value = applyFilters(value, directive); } // 調(diào)用update方法 directive.update(directive.el, value, directive.argument, directive); }); } }); } /** * 調(diào)用filters依次處理value * @param {任意類型} value 數(shù)據(jù)值 * @param {Object} directive 解析出來(lái)的指令對(duì)象 */ function applyFilters(value, directive) { if (directive.definition.customFilter) { return directive.definition.customFilter(value, directive.filters); } else { directive.filters.forEach((name) => { if (Filters[name]) { value = Filters[name](value); } }); return value; } }
其中的bindings存放了數(shù)據(jù)和指令的關(guān)系,該對(duì)象中的key為opts.scope中的屬性,value為Object,如下:
{ "msg": { "value": undefined, "directives": [] // 上面介紹的directive對(duì)象 } }
數(shù)據(jù)與directive建立好關(guān)系之后, bindAccessors 中為seed的scope對(duì)象的屬性重新定義了getter和setter,其中setter會(huì)調(diào)用指令update方法,到此就已經(jīng)完事具備了。
Seed構(gòu)造函數(shù)在實(shí)例化的最后會(huì)迭代bindings中的key,然后從opts.scope找到對(duì)應(yīng)的value, 賦值給了scope對(duì)象,此時(shí)setter中的update就觸發(fā)執(zhí)行了。
下面再看一下 sd-on 指令的定義:
{ on: { update: function(el, handler, event, directive) { if (!directive.handlers) { directive.handlers = {}; } const handlers = directive.handlers; if (handlers[event]) { el.removeEventListener(event, handlers[event]); } if (handler) { handler = handler.bind(el); el.addEventListener(event, handler); handlers[event] = handler; } }, customFilter: function(handler, selectors) { return function(e) { const match = selectors.every((selector) => e.target.matches(selector)); if (match) { handler.apply(this, arguments); } } } } }
發(fā)現(xiàn)它有customFilter,其實(shí)在 applyFilters 中就是針對(duì)該指令做的一個(gè)單獨(dú)的判斷,其中的selectors就是[".button"],最終返回一個(gè)匿名函數(shù)(事件監(jiān)聽(tīng)函數(shù)),該匿名函數(shù)當(dāng)做value傳遞給update方法,被其handler接收,update方法處理的是事件的綁定。這里其實(shí)實(shí)現(xiàn)的是事件的代理功能,customFilter中將handler包裝一層作為事件的監(jiān)聽(tīng)函數(shù),同時(shí)還實(shí)現(xiàn)事件代理功能,設(shè)計(jì)的比較巧妙!
總結(jié)
以上所述是小編給大家介紹的vue 中directive的簡(jiǎn)單實(shí)現(xiàn),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
基于vue+echarts實(shí)現(xiàn)柱狀圖漸變色效果(每個(gè)柱子顏色不同)
前段時(shí)間的vue項(xiàng)目中用到了echarts柱狀圖,由于UI設(shè)計(jì)稿中要求使用漸變色,并且每個(gè)柱子的顏色不同,于是做了一番研究,現(xiàn)將我的實(shí)現(xiàn)方案分享如下2024-05-05Vue開(kāi)發(fā)中出現(xiàn)Loading?Chunk?Failed的問(wèn)題解決
本文主要介紹了Vue開(kāi)發(fā)中出現(xiàn)Loading?Chunk?Failed的問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-03-03vue-cli+webpack項(xiàng)目 修改項(xiàng)目名稱的方法
下面小編就為大家分享一篇vue-cli+webpack項(xiàng)目 修改項(xiàng)目名稱的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-02-02快速解決Error: error:0308010C:digital envelope ro
因?yàn)?nbsp;node.js V17版本中最近發(fā)布的OpenSSL3.0, 而OpenSSL3.0對(duì)允許算法和密鑰大小增加了嚴(yán)格的限制,下面通過(guò)本文給大家分享快速解決Error: error:0308010C:digital envelope routines::unsupported的三種解決方案,感興趣的朋友一起看看吧2024-02-02vue.js使用v-model實(shí)現(xiàn)父子組件間的雙向通信示例
這篇文章主要介紹了vue.js使用v-model實(shí)現(xiàn)父子組件間的雙向通信,結(jié)合實(shí)例形式分析了vue.js基于v-model父子組件間的雙向通信的具體實(shí)現(xiàn)技巧,需要的朋友可以參考下2020-02-02vue-cli創(chuàng)建的項(xiàng)目,配置多頁(yè)面的實(shí)現(xiàn)方法
下面小編就為大家分享一篇vue-cli創(chuàng)建的項(xiàng)目,配置多頁(yè)面的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-03-03Vue中axios的封裝(報(bào)錯(cuò)、鑒權(quán)、跳轉(zhuǎn)、攔截、提示)
這篇文章主要介紹了Vue中axios的封裝(報(bào)錯(cuò)、鑒權(quán)、跳轉(zhuǎn)、攔截、提示),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08