Vue2.x響應式簡單講解及示例
vue響應式,我們都很熟悉了。當我們修改vue中data對象中的屬性時,頁面中引用該屬性的地方就會發(fā)生相應的改變。避免了我們再去操作dom,進行數據綁定。
二、Vue響應式實現分析對于vue的響應式原理,官網上給了出文字描述 https://cn.vuejs.org/v2/guide/reactivity.html 。
vue內部主要是通過數據劫持和觀察者模式實現的
數據劫持:
vue2.x內部使用Object.defineProperty https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
vue3.x內部使用的Proxy https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy
觀察者模式:https://www.jb51.net/article/219790.htm
內部成員示意圖
各個成員的功能
Vue:
把data中的成員注入到Vue實例中,并把data中的成員轉換為getter和setter
Observer:
對data對象中的簡單類型數據及對象進行監(jiān)聽,當數據發(fā)生變化時通知Dep
Compiler:
解析每個元素中的指令/差值表達式,并替換成相應的數據
Dep:
觀察者模式中的通知者,添加觀察者,當數據變化時通知觀察者
Watcher:
每個引用data中的屬性的地方都有一個watcher對象,負責更新視圖
附:data對象中的屬性充當被觀察者,引用data對象中屬性的地方充當觀察者
三、Vue響應式源碼實現Vue對象實現
功能
負責接受初始化的參數 把data中的屬性注入到data實例,轉換成getter和setter 調用Observer監(jiān)聽data中所有屬性的變化 調用compiler解析指令、差值表達式.class Vue{ constructor(options){// 1、通過屬性保存穿進來的屬性this.$options= options||{};this.$data= options.data||{};this.$el = typeof options.el ===’string’ ? document.querySelector(options.el) : options.el;// 2、把data參數中的數據轉換為getter和setter 掛載到Vue實例上this._proxyData(this.$data)// 3、調用observe對象監(jiān)視data數據的變化new Observer(this.$data)// 4、調用compiler對象渲染頁面new Compiler(this) } _proxyData(data){if (data&&Object.keys(data).length>0){ for (const key in data) {Object.defineProperty(this,key,{ configurable:true, enumerable:true, get(){return data[key] }, set(value){if (data[key]===value) { return;}data[key]=value; }}) }} }}
Observer對象實現
功能
把data選項中的屬性進行數據劫持 data中的某個屬性也是對象的話,進行遞歸轉換成響應式對象 數據變化發(fā)送通知//數據劫持 class Observer { constructor(data) {this.walk(data) } walk(data) { //1、判斷data是否是對象 if (!data || typeof data !== ’object’) { return}//2、循環(huán)調用defineReactive進行數據劫持Object.keys(data).forEach(key => { this.defineReactive(data, key, data[key])}) } defineReactive(obj, key, val) {//創(chuàng)建通知者const dep = new Dep()//使用walk把引用對象中的屬性變成響應式的this.walk(val)const that=this;Object.defineProperty(obj, key, { configurable: true, enumerable: true, get() {//通知者收集觀察者Dep.target && dep.addSub(Dep.target)return val; }, set(newVal) {if (newVal === val) { return;}val = newVal;that.walk(newVal)//被觀察者發(fā)生變化的時候,通知者對象給每個觀察者發(fā)送通知dep.notify() }}) }}
Compile對象實現
功能
負責編譯模板,解析指令、差值表達式 負責頁面首次渲染 當數據發(fā)生改變后,負責重新渲染視圖//編譯器 class Compiler { constructor(vm) {this.el = vm.$el;this.vm = vm;this.compile(this.el) } //編譯模板 判斷節(jié)點是文本節(jié)點還是元素節(jié)點 compile(el) {let childNodes = el.childNodes;//處理第一層子節(jié)點Array.from(childNodes).forEach(node => { if (this.isTextNode(node)) {this.compileText(node) } else if (this.isElementNode(node)) {this.compileElement(node) } //如果當前節(jié)點還有子節(jié)點 遞歸調用編譯指令 if (node.childNodes && node.childNodes.length) {this.compile(node) }}) } //編譯元素節(jié)點,處理指令 compileElement(node) { //遍歷所有的指令Array.from(node.attributes).forEach(attr => { //判斷是不是指令節(jié)點 if (this.isDirective(attr.name)) {const nodeName = attr.name;const key = attr.nodeValue;const directive = nodeName.substr(2)this.updater(directive,node,key) }}) } updater(directive,node,key){const updaterFn = this[directive+'Updater']updaterFn && updaterFn.call(this,node,this.vm[key],key) } //v-text textUpdater(node,value,key){node.textContent=value//使用v-text表達式的地方就是一個觀察者new Watcher(this.vm,key,newValue => { node.textContent = newValue}) } //v-model modelUpdater(node,value,key){node.value =value//使用v-model表達式的地方就是一個觀察者new Watcher(this.vm,key,newValue => { node.value = newValue}) //實現雙向綁定node.addEventListener(’input’,()=>{ this.vm[key] = node.value}) } //v-html htmlUpdater(node,value,key){node.innerHTML = value//使用v-html表達式的地方就是一個觀察者new Watcher(this.vm,key,newValue => { node.innerHTML = newValue}) } //處理差值表達式 compileText(node) {//匹配差值表達式的正則let reg = /{{(.+?)}}///用正則匹配node的textContent,如果匹配到了 就替換if (reg.test(node.textContent)) { //獲取插值表達式的key let key = RegExp.$1; let value = node.textContent; node.textContent = value.replace(reg, this.vm[key]) //使用差值表達式的地方就是一個觀察者 new Watcher(this.vm,key,newValue => {node.textContent = newValue })} } //是否是指令 isDirective(attrName) {return attrName.startsWith(’v-’) } //是否是文本節(jié)點 isTextNode(node) {return node.nodeType === 3 } //是否是元素 isElementNode(node) {return node.nodeType === 1 }}
Dep對象實現
功能
收集依賴,添加觀察者 通知所有觀察者//通知者類 class Dep { constructor() {//存儲觀察者this.subs = [] } /** * 收集觀察者 */ addSub(sub) {if (sub && sub.update) { this.subs.push(sub)} } /** * 通知觀察者改變狀態(tài) */ notify() {this.subs.forEach(sub => { sub.update()}) }}
Watcher對象實現
功能
當數據變化時,Dep通知所有Watcher實例更新視圖 自身實例化的時候往Dep對象中添加自己//觀察者類 class Watcher { constructor (vm,key,cb) {//Vue實例this.vm =vm;// data中的key對象this.key =key;// 更新視圖的回調函數this.cb = cb//把當前觀察者實例存放在Dep的target靜態(tài)屬性中Dep.target =this//觸發(fā)Observe的getter方法,把當前實例存放在Dep.subs中//data中key對應的舊值this.oldValue = this.vm[this.key]Dep.target = null } //每個觀察者都有一個update方法來改變狀態(tài) update(){const newValue = this.vm[this.key]if ( this.newValue === this.oldValue ) { return}this.cb(newValue) }}
測試
<head> <meta charset='UTF-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>index</title> <script src='http://m.cgvv.com.cn/bcjs/js/dep.js'></script> <script src='http://m.cgvv.com.cn/bcjs/js/watcher.js'></script> <script src='http://m.cgvv.com.cn/bcjs/js/compiler.js'></script> <script src='http://m.cgvv.com.cn/bcjs/js/observer.js'></script> <script src='http://m.cgvv.com.cn/bcjs/js/vue.js'></script></head><body> <p id='app'><h1>差值表達式</h1><h3>{{msg}}</h3><h3>{{count}}</h3><h1>v-text</h1><p v-text=’msg’></p><h1>v-model</h1><input type='text' v-model='msg' attr='msg'><input type='text' v-model='count'><h1>v-html</h1><p v-html='htmlText'></p> </p> <script>let vm = new Vue({ el:'#app', data:{msg:’信息’,count:’數量’, person:{name:’張三’},htmlText:'<p style=’color:red’>你好</p>' }}) </script></body>
到此這篇關于Vue2.x響應式簡單講解及示例的文章就介紹到這了,更多相關Vue2.x響應式內容請搜索好吧啦網以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
