vue 中directive功能的簡單實現(xiàn)
2018年首個計劃是學習vue源碼,查閱了一番資料之后,決定從第一個commit開始看起,這將是一場持久戰(zhàn)!本篇介紹directive的簡單實現(xiàn),主要學習其實現(xiàn)的思路及代碼的設計(directive和filter擴展起來非常方便,符合設計模式中的 開閉原則 )。
構思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; } } });
實現(xiàn)功能夠簡單吧--將scope中的數(shù)據(jù)綁定到app中。
核心邏輯設計
指令格式
以 sd-text="msg | capitalize" 為例說明:
- sd 為統(tǒng)一的前綴標識
- text 為指令名稱
- capitalize 為過濾器名稱
其中 | 后面為過濾器,可以添加多個。 sd-class-red
中的red為參數(shù)。
代碼結(jié)構介紹
main.js 入口文件
// Seed構造函數(shù) const Seed = function(opts) { }; // 對外暴露的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); } };
就這三個文件,其中directives和filters都是配置文件,很易于擴展。
實現(xiàn)的大致思路如下:
1.在Seed實例創(chuàng)建的時候會依次解析el容器中node節(jié)點的指令
2.將指令解析結(jié)果封裝為指令對象,結(jié)構為:
屬性 | 說明 | 類型 |
---|---|---|
attr | 原始屬性,如 sd-text |
String |
key | 對應scope對象中的屬性名稱 | String |
filters | 過濾器名稱列表 | Array |
definition | 該指令的定義,如text對應的函數(shù) | Function |
argument | 從attr中解析出來的參數(shù)(只支持一個參數(shù)) | String |
update | 更新directive時調(diào)用 typeof def === 'function' ? def : def.update |
Function |
bind | 如果directive中定義了bind方法,則在 bindDirective 中會調(diào)用 |
Function |
el | 存儲當前element元素 | Element |
3.想辦法執(zhí)行指令的update方法即可,該插件使用了 Object.defineProperty 來定義scope中的每個屬性,在其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é)點 [].forEach.call(els, processNode); // 解析根節(jié)點 processNode(root); // 給scope賦值,觸發(fā)setter方法,此時會調(diào)用與其相對應的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 主要做了兩件事一個是 parseDirective ,另一個是 bindDirective 。
先來看看 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" 為例來說明,其中attr對象的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實例對象 * @param {Element} el 當前node節(jié)點 * @param {Object} bindings 數(shù)據(jù)綁定存儲對象 * @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ù)相關的指令 }; } directive.el = el; binding.directives.push(directive); if (!seed.scope.hasOwnProperty(key)) { bindAccessors(seed, key, binding); } } /** * 重寫scope西鄉(xiāng)屬性的getter和setter * @param {Seed} seed Seed實例 * @param {String} key 對象屬性即opts.scope中的屬性 * @param {Object} binding 數(shù)據(jù)綁定關系對象 */ 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) => { // 如果有過濾器則先執(zhí)行過濾器 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 解析出來的指令對象 */ 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ù)和指令的關系,該對象中的key為opts.scope中的屬性,value為Object,如下:
{ "msg": { "value": undefined, "directives": [] // 上面介紹的directive對象 } }
數(shù)據(jù)與directive建立好關系之后, bindAccessors 中為seed的scope對象的屬性重新定義了getter和setter,其中setter會調(diào)用指令update方法,到此就已經(jīng)完事具備了。
Seed構造函數(shù)在實例化的最后會迭代bindings中的key,然后從opts.scope找到對應的value, 賦值給了scope對象,此時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,其實在 applyFilters 中就是針對該指令做的一個單獨的判斷,其中的selectors就是[".button"],最終返回一個匿名函數(shù)(事件監(jiān)聽函數(shù)),該匿名函數(shù)當做value傳遞給update方法,被其handler接收,update方法處理的是事件的綁定。這里其實實現(xiàn)的是事件的代理功能,customFilter中將handler包裝一層作為事件的監(jiān)聽函數(shù),同時還實現(xiàn)事件代理功能,設計的比較巧妙!
總結(jié)
以上所述是小編給大家介紹的vue 中directive的簡單實現(xiàn),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
基于vue+echarts實現(xiàn)柱狀圖漸變色效果(每個柱子顏色不同)
前段時間的vue項目中用到了echarts柱狀圖,由于UI設計稿中要求使用漸變色,并且每個柱子的顏色不同,于是做了一番研究,現(xiàn)將我的實現(xiàn)方案分享如下2024-05-05Vue開發(fā)中出現(xiàn)Loading?Chunk?Failed的問題解決
本文主要介紹了Vue開發(fā)中出現(xiàn)Loading?Chunk?Failed的問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-03-03快速解決Error: error:0308010C:digital envelope ro
因為 node.js V17版本中最近發(fā)布的OpenSSL3.0, 而OpenSSL3.0對允許算法和密鑰大小增加了嚴格的限制,下面通過本文給大家分享快速解決Error: error:0308010C:digital envelope routines::unsupported的三種解決方案,感興趣的朋友一起看看吧2024-02-02vue.js使用v-model實現(xiàn)父子組件間的雙向通信示例
這篇文章主要介紹了vue.js使用v-model實現(xiàn)父子組件間的雙向通信,結(jié)合實例形式分析了vue.js基于v-model父子組件間的雙向通信的具體實現(xiàn)技巧,需要的朋友可以參考下2020-02-02vue-cli創(chuàng)建的項目,配置多頁面的實現(xiàn)方法
下面小編就為大家分享一篇vue-cli創(chuàng)建的項目,配置多頁面的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03Vue中axios的封裝(報錯、鑒權、跳轉(zhuǎn)、攔截、提示)
這篇文章主要介紹了Vue中axios的封裝(報錯、鑒權、跳轉(zhuǎn)、攔截、提示),本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08