Vue數(shù)據(jù)雙向綁定原理及簡(jiǎn)單實(shí)現(xiàn)方法
Vue這個(gè)框架就不簡(jiǎn)單介紹了,它最大的特性就是數(shù)據(jù)的雙向綁定以及虛擬dom.核心就是用數(shù)據(jù)來(lái)驅(qū)動(dòng)視圖層的改變.先看一段代碼.
一、示例
var vm = new Vue({ data: { obj: { a: 1 } }, created: function () { console.log(this.obj); } });
二、實(shí)現(xiàn)原理
vue數(shù)據(jù)雙向綁定是通過(guò)數(shù)據(jù)劫持結(jié)合發(fā)布者-訂閱者模式的方式來(lái)實(shí)現(xiàn)的.
1)數(shù)據(jù)劫持、vue是通過(guò)Object.defineProperty()來(lái)實(shí)現(xiàn)數(shù)據(jù)劫持,其中會(huì)有g(shù)etter()和setter方法;當(dāng)讀取屬性值時(shí),就會(huì)觸發(fā)getter()方法,在view中如果數(shù)據(jù)發(fā)生了變化,就會(huì)通過(guò)Object.defineProperty( )對(duì)屬性設(shè)置一個(gè)setter函數(shù),當(dāng)數(shù)據(jù)改變了就會(huì)來(lái)觸發(fā)這個(gè)函數(shù);
三、實(shí)現(xiàn)步驟
1、實(shí)現(xiàn)Observer
ok, 思路已經(jīng)整理完畢,也已經(jīng)比較明確相關(guān)邏輯和模塊功能了,let's do it
我們知道可以利用Obeject.defineProperty()來(lái)監(jiān)聽(tīng)屬性變動(dòng)
那么將需要observe的數(shù)據(jù)對(duì)象進(jìn)行遞歸遍歷,包括子屬性對(duì)象的屬性,都加上 setter和getter
這樣的話,給這個(gè)對(duì)象的某個(gè)值賦值,就會(huì)觸發(fā)setter,那么就能監(jiān)聽(tīng)到了數(shù)據(jù)變化。。相關(guān)代碼可以是這樣:
var data = {name: 'kindeng'}; observe(data); data.name = 'dmq'; // 哈哈哈,監(jiān)聽(tīng)到值變化了 kindeng --> dmq function observe(data) { if (!data || typeof data !== 'object') { return; } // 取出所有屬性遍歷 Object.keys(data).forEach(function(key) { defineReactive(data, key, data[key]); }); }; function defineReactive(data, key, val) { observe(val); // 監(jiān)聽(tīng)子屬性 Object.defineProperty(data, key, { enumerable: true, // 可枚舉 configurable: false, // 不能再define get: function() { return val; }, set: function(newVal) { console.log('哈哈哈,監(jiān)聽(tīng)到值變化了 ', val, ' --> ', newVal); val = newVal; } }); }
這樣我們已經(jīng)可以監(jiān)聽(tīng)每個(gè)數(shù)據(jù)的變化了,那么監(jiān)聽(tīng)到變化之后就是怎么通知訂閱者了,所以接下來(lái)我們需要實(shí)現(xiàn)一個(gè)消息訂閱器,很簡(jiǎn)單,維護(hù)一個(gè)數(shù)組,用來(lái)收集訂閱者,數(shù)據(jù)變動(dòng)觸發(fā)notify,再調(diào)用訂閱者的update方法,代碼改善之后是這樣:
// ... 省略 function defineReactive(data, key, val) { var dep = new Dep(); observe(val); // 監(jiān)聽(tīng)子屬性 Object.defineProperty(data, key, { // ... 省略 set: function(newVal) { if (val === newVal) return; console.log('哈哈哈,監(jiān)聽(tīng)到值變化了 ', val, ' --> ', newVal); val = newVal; dep.notify(); // 通知所有訂閱者 } }); } function Dep() { this.subs = []; } Dep.prototype = { addSub: function(sub) { this.subs.push(sub); }, notify: function() { this.subs.forEach(function(sub) { sub.update(); }); } };
那么問(wèn)題來(lái)了,誰(shuí)是訂閱者?怎么往訂閱器添加訂閱者?
沒(méi)錯(cuò),上面的思路整理中我們已經(jīng)明確訂閱者應(yīng)該是Watcher, 而且var dep = new Dep();
是在 defineReactive方法內(nèi)部定義的,所以想通過(guò)dep添加訂閱者,就必須要在閉包內(nèi)操作,所以我們可以在 getter里面動(dòng)手腳:
// Observer.js // ...省略 Object.defineProperty(data, key, { get: function() { // 由于需要在閉包內(nèi)添加watcher,所以通過(guò)Dep定義一個(gè)全局target屬性,暫存watcher, 添加完移除 Dep.target && dep.addDep(Dep.target); return val; } // ... 省略 }); // Watcher.js Watcher.prototype = { get: function(key) { Dep.target = this; this.value = data[key]; // 這里會(huì)觸發(fā)屬性的getter,從而添加訂閱者 Dep.target = null; } }
這里已經(jīng)實(shí)現(xiàn)了一個(gè)Observer了,已經(jīng)具備了監(jiān)聽(tīng)數(shù)據(jù)和數(shù)據(jù)變化通知訂閱者的功能,完整代碼。那么接下來(lái)就是實(shí)現(xiàn)Compile了
2、實(shí)現(xiàn)Compile
compile主要做的事情是解析模板指令,將模板中的變量替換成數(shù)據(jù),然后初始化渲染頁(yè)面視圖,并將每個(gè)指令對(duì)應(yīng)的節(jié)點(diǎn)綁定更新函數(shù),添加監(jiān)聽(tīng)數(shù)據(jù)的訂閱者,一旦數(shù)據(jù)有變動(dòng),收到通知,更新視圖,如圖所示:
圖片描述
因?yàn)楸闅v解析的過(guò)程有多次操作dom節(jié)點(diǎn),為提高性能和效率,會(huì)先將跟節(jié)點(diǎn)el轉(zhuǎn)換成文檔碎片fragment進(jìn)行解析編譯操作,解析完成,再將fragment添加回原來(lái)的真實(shí)dom節(jié)點(diǎn)中
function Compile(el) { this.$el = this.isElementNode(el) ? el : document.querySelector(el); if (this.$el) { this.$fragment = this.node2Fragment(this.$el); this.init(); this.$el.appendChild(this.$fragment); } } Compile.prototype = { init: function() { this.compileElement(this.$fragment); }, node2Fragment: function(el) { var fragment = document.createDocumentFragment(), child; // 將原生節(jié)點(diǎn)拷貝到fragment while (child = el.firstChild) { fragment.appendChild(child); } return fragment; } }; compileElement方法將遍歷所有節(jié)點(diǎn)及其子節(jié)點(diǎn),進(jìn)行掃描解析編譯,調(diào)用對(duì)應(yīng)的指令渲染函數(shù)進(jìn)行數(shù)據(jù)渲染,并調(diào)用對(duì)應(yīng)的指令更新函數(shù)進(jìn)行綁定,詳看代碼及注釋說(shuō)明: Compile.prototype = { // ... 省略 compileElement: function(el) { var childNodes = el.childNodes, me = this; [].slice.call(childNodes).forEach(function(node) { var text = node.textContent; var reg = /\{\{(.*)\}\}/; // 表達(dá)式文本 // 按元素節(jié)點(diǎn)方式編譯 if (me.isElementNode(node)) { me.compile(node); } else if (me.isTextNode(node) && reg.test(text)) { me.compileText(node, RegExp.$1); } // 遍歷編譯子節(jié)點(diǎn) if (node.childNodes && node.childNodes.length) { me.compileElement(node); } }); }, compile: function(node) { var nodeAttrs = node.attributes, me = this; [].slice.call(nodeAttrs).forEach(function(attr) { // 規(guī)定:指令以 v-xxx 命名 // 如 <span v-text="content"></span> 中指令為 v-text var attrName = attr.name; // v-text if (me.isDirective(attrName)) { var exp = attr.value; // content var dir = attrName.substring(2); // text if (me.isEventDirective(dir)) { // 事件指令, 如 v-on:click compileUtil.eventHandler(node, me.$vm, exp, dir); } else { // 普通指令 compileUtil[dir] && compileUtil[dir](node, me.$vm, exp); } } }); } }; // 指令處理集合 var compileUtil = { text: function(node, vm, exp) { this.bind(node, vm, exp, 'text'); }, // ...省略 bind: function(node, vm, exp, dir) { var updaterFn = updater[dir + 'Updater']; // 第一次初始化視圖 updaterFn && updaterFn(node, vm[exp]); // 實(shí)例化訂閱者,此操作會(huì)在對(duì)應(yīng)的屬性消息訂閱器中添加了該訂閱者watcher new Watcher(vm, exp, function(value, oldValue) { // 一旦屬性值有變化,會(huì)收到通知執(zhí)行此更新函數(shù),更新視圖 updaterFn && updaterFn(node, value, oldValue); }); } }; // 更新函數(shù) var updater = { textUpdater: function(node, value) { node.textContent = typeof value == 'undefined' ? '' : value; } // ...省略 };
這里通過(guò)遞歸遍歷保證了每個(gè)節(jié)點(diǎn)及子節(jié)點(diǎn)都會(huì)解析編譯到,包括了{(lán){}}表達(dá)式聲明的文本節(jié)點(diǎn)。指令的聲明規(guī)定是通過(guò)特定前綴的節(jié)點(diǎn)屬性來(lái)標(biāo)記,如<span v-text="content"
other-attr中v-text便是指令,而other-attr不是指令,只是普通的屬性。
監(jiān)聽(tīng)數(shù)據(jù)、綁定更新函數(shù)的處理是在compileUtil.bind()這個(gè)方法中,通過(guò)new Watcher()添加回調(diào)來(lái)接收數(shù)據(jù)變化的通知
至此,一個(gè)簡(jiǎn)單的Compile就完成了,完整代碼。接下來(lái)要看看Watcher這個(gè)訂閱者的具體實(shí)現(xiàn)了
3、實(shí)現(xiàn)Watcher
Watcher訂閱者作為Observer和Compile之間通信的橋梁,主要做的事情是:
1、在自身實(shí)例化時(shí)往屬性訂閱器(dep)里面添加自己
2、自身必須有一個(gè)update()方法
3、待屬性變動(dòng)dep.notice()通知時(shí),能調(diào)用自身的update()方法,并觸發(fā)Compile中綁定的回調(diào),則功成身退。
如果有點(diǎn)亂,可以回顧下前面的思路整理
function Watcher(vm, exp, cb) { this.cb = cb; this.vm = vm; this.exp = exp; // 此處為了觸發(fā)屬性的getter,從而在dep添加自己,結(jié)合Observer更易理解 this.value = this.get(); } Watcher.prototype = { update: function() { this.run(); // 屬性值變化收到通知 }, run: function() { var value = this.get(); // 取到最新值 var oldVal = this.value; if (value !== oldVal) { this.value = value; this.cb.call(this.vm, value, oldVal); // 執(zhí)行Compile中綁定的回調(diào),更新視圖 } }, get: function() { Dep.target = this; // 將當(dāng)前訂閱者指向自己 var value = this.vm[exp]; // 觸發(fā)getter,添加自己到屬性訂閱器中 Dep.target = null; // 添加完畢,重置 return value; } }; // 這里再次列出Observer和Dep,方便理解 Object.defineProperty(data, key, { get: function() { // 由于需要在閉包內(nèi)添加watcher,所以可以在Dep定義一個(gè)全局target屬性,暫存watcher, 添加完移除 Dep.target && dep.addDep(Dep.target); return val; } // ... 省略 }); Dep.prototype = { notify: function() { this.subs.forEach(function(sub) { sub.update(); // 調(diào)用訂閱者的update方法,通知變化 }); } };
實(shí)例化Watcher的時(shí)候,調(diào)用get()方法,通過(guò)Dep.target = watcherInstance標(biāo)記訂閱者是當(dāng)前watcher實(shí)例,強(qiáng)行觸發(fā)屬性定義的getter方法,getter方法執(zhí)行的時(shí)候,就會(huì)在屬性的訂閱器dep添加當(dāng)前watcher實(shí)例,從而在屬性值有變化的時(shí)候,watcherInstance就能收到更新通知。
四、簡(jiǎn)單實(shí)現(xiàn)方法
<body> <div id="app"> <input type="text" id="txt"> <p id="show-txt"></p> </div> <script> var obj = {} Object.defineProperty(obj, 'txt', { get: function () { return obj }, set: function (newValue) { document.getElementById('txt').value = newValue document.getElementById('show-txt').innerHTML = newValue } }) document.addEventListener('keyup', function (e) { obj.txt = e.target.value }) </script> </body>
總結(jié)
以上所述是小編給大家介紹的Vue數(shù)據(jù)雙向綁定原理及簡(jiǎn)單實(shí)現(xiàn)方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- 關(guān)于Vue3父子組件emit參數(shù)傳遞問(wèn)題(解決Vue2this.$emit無(wú)效問(wèn)題)
- vue3?父子組件間相互傳值方式
- Vue3父子組件互調(diào)方法的實(shí)現(xiàn)
- vue3父子組件傳值中props使用細(xì)節(jié)淺析
- vue 數(shù)據(jù)雙向綁定的實(shí)現(xiàn)方法
- vue子組件改變父組件傳遞的prop值通過(guò)sync實(shí)現(xiàn)數(shù)據(jù)雙向綁定(DEMO)
- 詳解基于Vue的支持?jǐn)?shù)據(jù)雙向綁定的select組件
- Vue 父子組件實(shí)現(xiàn)數(shù)據(jù)雙向綁定效果的兩種方式(案例代碼)
相關(guān)文章
vue項(xiàng)目實(shí)現(xiàn)搜索內(nèi)容變紅色顯示
這篇文章主要為大家介紹了vue項(xiàng)目實(shí)現(xiàn)搜索內(nèi)容變紅色顯示,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12vue.js前端網(wǎng)頁(yè)彈框異步行為示例分析
這篇文章主要為大家介紹了vue.js前端網(wǎng)頁(yè)彈框異步的行為示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助祝大家多多進(jìn)步,早日升職加薪2021-11-11一文詳解Vue如何整合Echarts實(shí)現(xiàn)可視化界面
ECharts,縮寫來(lái)自Enterprise Charts,商業(yè)級(jí)數(shù)據(jù)圖表,一個(gè)純Javascript的圖表庫(kù),可以流暢的運(yùn)行在PC和移動(dòng)設(shè)備上。本文將在Vue中整合Echarts實(shí)現(xiàn)可視化界面,感興趣的可以了解一下2022-04-04vue 組件數(shù)據(jù)加載解析順序的詳細(xì)代碼
Vue.js的解析順序可以概括為:模板編譯、組件創(chuàng)建、數(shù)據(jù)渲染、事件處理和生命周期鉤子函數(shù)執(zhí)行,接下來(lái)通過(guò)本文給大家介紹vue 組件數(shù)據(jù)加載解析順序的完整代碼,感興趣的朋友跟隨小編一起看看吧2024-03-03element el-input directive數(shù)字進(jìn)行控制
本文介紹了vue使用directive 進(jìn)行控制的方法,使用element開(kāi)發(fā)的過(guò)程中遇到循環(huán)的數(shù)據(jù)只能輸入數(shù)字,并且有不要小數(shù)點(diǎn),有需要小數(shù)點(diǎn)的,就有一定的參考價(jià)值,有興趣的可以了解一下2018-10-10Element?Plus在el-form-item中設(shè)置justify-content無(wú)效的解決方案
這篇文章主要介紹了Element?Plus在el-form-item中設(shè)置justify-content無(wú)效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10