基於vue2.0原理-自己實現MVVM框架之computed計算屬性

基於上一篇data的雙向綁定,這一篇來聊聊computed的實現原理及自己實現計算屬性。

一、先聊下Computed的用法

寫一個最簡單的小demo,展示用戶的名字和年齡,代碼如下:

<body>
  <div id="app">
    <input type="text" v-model="name"><br/>
    <input type="text" v-model="age"><br/>
    {{NameAge}}
  </div>
  <script>
    var vm = new MYVM({
      el: '#app',
      data: {
        name: 'James',
        age:18
      },
      computed:{
        NameAge(){
          return this.$data.name+" "+this.$data.age;
        }
      },
    })
  </script>
</body>

運行結果:

iShot_2022-07-16_17.38.21

從代碼和運行效果可以看出,計算屬性NameAge依賴於data的name屬性和age屬性。

特點:

1、計算屬性是響應式的

2、依賴其它響應式屬性或計算屬性,當依賴的屬性有變化時重新計算屬性

3、計算結果有緩存,組件使用同一個計算屬性,只會計算一次,提高效率

4、不支持異步

適用場景:

當一個屬性受多個屬性影響時就需要用到computed

例如:購物車計算價格
只要購買數量,購買價格,優惠券,折扣券等任意一個發生變化,總價都會自動跟蹤變化。

二、原理分析

1、 computed 屬性解析

每個 computed 屬性都會生成對應的觀察者(Watcher 實例),觀察者存在 values 屬性和 get 方法。computed 屬性的 getter 函數會在 get 方法中調用,並將返回值賦值給 value。初始設置 dirty 和 lazy 的值爲 true,lazy 爲 true 不會立即 get 方法(懶執行),而是會在讀取 computed 值時執行。

function initComputed(vm, computed) {    
		// 存放computed的觀察者
    var watchers = vm._computedWatchers = Object.create(null);    
    //遍歷computed屬性
    for (var key in computed) {        
        //獲取屬性值,值可能是函數或對象
        var userDef = computed[key];        
        //當值是一個函數的時候,把函數賦值給getter;當值是對象的時候把get賦值給getter
        var getter = typeof userDef === 'function' ? userDef: userDef.get;      
      
        // 每個 computed 都創建一個 watcher
        // 創建watcher實例 用來存儲計算值,判斷是否需要重新計算
        watchers[key] = new Watcher(vm, getter, { 
             lazy: true 
        });        

        // 判斷是否有重名的屬性
        if (! (key in vm)) {
            defineComputed(vm, key, userDef);
        }
    }
}

代碼中省略不需要關心的代碼,在initComputed中,Vue做了這些事情:

  1. 爲每一個computed建立了watcher。

  2. 收集所有computed的watcher,並綁定在Vue實例的_computedWatchers 上。

  3. defineComputed 處理每一個computed。

2、將computed屬性添加到組件實例上

function defineComputed(target, key, userDef) {    
    // 設置 set 爲默認值,避免 computed 並沒有設置 set
    var set = function(){}      
    //  如果用戶設置了set,就使用用戶的set
    if (userDef.set) set = userDef.set   
    Object.defineProperty(target, key, {        
        // 包裝get 函數,主要用於判斷計算緩存結果是否有效
        get:createComputedGetter(key),        
        set:set

    });
}
// 重定義的getter函數
function createComputedGetter(key) {
    return function computedGetter() {
        var watcher = this._computedWatchers && this._computedWatchers[key];
        if (watcher) {
            if (watcher.dirty) {
                // true,懶執行
                watcher.evaluate(); // 執行watcher方法後設置dirty爲false
            }
            if (Dep.target) {
                watcher.depend();
            }
            return watcher.value; //返回觀察者的value值
        }
    };
}
  1. 使用 Object.defineProperty 爲實例上computed 屬性建立get、set方法。

  2. set 函數默認是空函數,如果用戶設置,則使用用戶設置。

  3. createComputedGetter 包裝返回 get 函數。

3、頁面初始化時

頁面初始化時,會讀取computed屬性值,觸發重新定義的getter,由於觀察者的dirty值爲true,將會調用原始的getter函數,當getter方法讀取data數據時會觸發原始的get方法(數據劫持中的get方法),將computed對應的watcher添加到data依賴收集器(dep)中。觀察者的get方法執行完後,更新觀察者的value,並將dirty置爲false,表示value值已更新,之後執行觀察者的depend方法,將上層觀察者也添加到getter函數中data的依賴收集器(dep)中,最後返回computed的value值;

image-20220726174919681

4、當 computed 屬性 getter 函數依賴的 data 值改變時

將會根據之前依賴收集的觀察者,依次調用觀察者的 update 方法,先調用 computed 觀察者的 update 方法,由於 lazy 爲 true,將會設置觀察者的 dirty 爲 true,表示 computed 屬性 getter 函數依賴的 data 值發生變化,但不調用觀察者的 get 方法更新 value 值。再調用包含頁面更新方法的觀察者的 update 方法,在更新頁面時會讀取 computed 屬性值,觸發重定義的 getter 函數,此時由於 computed 屬性的觀察者 dirty 爲 true,調用該觀察者的 get 方法,更新 value 值,並返回,完成頁面的渲染。

image-20220727135348649

5、核心流程

  1. 首次讀取 computed 屬性值時,dirty 值初始爲 true
  2. 根據getter計算屬性值,並保存在觀察者value上並設置dirty爲false
  3. 之後再讀取 computed 屬性值時,dirty 值爲 false,不調用 getter 重新計算值,直接返回觀察者中的value
  4. 當 computed 屬性getter依賴的data發生變化時,再次設置dirty爲true,通知頁面更新,重新計算屬性值

三、自定義實現

基於上一篇文章實現的自定義框架,增加computed屬性的解析和綁定。

1、首先在index.html定義並使用計算屬性

<body>
  <div id="app">
    <span v-text="name"></span>
    <input type="text" v-model="age">
    <input type="text" v-model="name">
    {{name}}<br/>
		{{fullName}}<br/>
    {{fullName}}<br/>
    {{fullName}}<br/>
    {{fullName}}<br/>
    {{fullNameAge}}<br/>
    {{fullNameAge}}<br/>
  </div>
  <script>
    var vm = new MYVM({
      el: '#app',
      data: {
        name: 'James',
        age:18
      },
      //定義計算屬性
      computed:{
        fullName(){
          return this.$data.name+" Li";
        },
        fullNameAge(){
          return this.$computed.fullName+" "+this.$data.age;
        }
      },
    })
  </script>
</body>
</html>

定義了兩個計算屬性fullName和fullNameAge,並在模板中進行了調用。

2、MYVM.js中增加對計算屬性的解析和處理

function MYVM(options){
     //屬性初始化
     this.$vm=this;
     this.$el=options.el;
     this.$data=options.data;
     //獲取computed屬性
     this.$computed=options.computed;
     //定義管理computed觀察者的屬性
     this.$computedWatcherManage={};
     
     //視圖必須存在
     if(this.$el){
        //添加屬性觀察對象(實現數據挾持)
        new Observer(this.$data)
        new ObserverComputed(this.$computed,this.$vm);

        // //創建模板編譯器,來解析視圖
        this.$compiler = new TemplateCompiler(this.$el, this.$vm)
    }
}

增加$computed屬性用來存儲計算屬性,$computedWatcherManage用來管理計算屬性的Watcher,ObserverComputed用來劫持計算屬性和生成對應的watcher。

3、ObserverComputed創建computed的Watcher實例,劫持computed屬性

//數據解析,完成對數據屬性的劫持
function ObserverComputed(computed,vm){
    this.vm=vm;
    //判斷computed是否有效且computed必須是對象
    if(!computed || typeof computed !=='object' ){
        return
    }else{
        var keys=Object.keys(computed)
        keys.forEach((key)=>{
            this.defineReactive(computed,key)
        })
    }
}
ObserverComputed.prototype.defineReactive=function(obj,key){
    //獲取計算屬性對應的方法
    let fun=obj[key];
    let vm=this.vm;
    //創建計算屬性的Watcher,存入到$computedWatcherManage
    vm.$computedWatcherManage[key]= new ComputedWatcher(vm, key, fun);
    let watcher= vm.$computedWatcherManage[key];

    Object.defineProperty(obj,key,{
        //是否可遍歷
        enumerable: true,
        //是否可刪除
        configurable: false,

        //get方法
        get(){
            //判斷是否需要重新計算屬性
            //dirty 是否使用緩存
            //$computedWatcherManage.dep 是否是創建Watcher收集依賴時執行
            if(watcher.dirty || vm.$computedWatcherManage.dep==true){
                let val=fun.call(vm)
                return val
            }else{
                //返回Watcher緩存的值
                return watcher.value
            }
            
        },
    })
}

vm.$computedWatcherManage[key]= new ComputedWatcher(vm, key, fun);創建Watcher實例

其它的註釋都比較細緻,不細說了哈

4、ComputedWatcher 緩存value,管理頁面訂閱者,更新頁面

//聲明一個訂閱者
//vm 全局vm對象
//expr 屬性名
//fun 屬性對應的計算方法
function ComputedWatcher(vm, expr,fun) {
    //初始化屬性
    this.vm = vm;
    this.expr = expr;
    this.fun=fun;
    //計算computed屬性的值,進行緩存
    this.value=this.get();
    //是否使用緩存
    this.dirty=false;
    //管理模板編譯後的訂閱者
    this.calls=[];
  }
  //執行computed屬性對應的方法,並進行依賴收集
  ComputedWatcher.prototype.get=function(){
        //設置全局Dep的target爲當前訂閱者
        Dep.target = this;
        //獲取屬性的當前值,獲取時會執行屬性的get方法,get方法會判斷target是否爲空,不爲空就添加訂閱者
        this.vm.$computedWatcherManage.dep=true
        var value = this.fun.call(this.vm)
        //清空全局
        Dep.target = null;
        this.vm.$computedWatcherManage.dep=false
        return value;
  }
  
  //添加模板編譯後的訂閱者
  ComputedWatcher.prototype.addCall=function(call){
    this.calls.push(call)
  }

  //更新模板
  ComputedWatcher.prototype.update=function(){
        this.dirty=true
        //獲取新值
        var newValue = this.vm.$computed[this.expr]
        //獲取老值
        var old = this.value;
        //判斷後
        if (newValue !== old) {
            this.value=newValue;
            this.calls.forEach(item=>{
                item(this.value)
            })
        }
        this.dirty=false
  }

ComputedWatcher核心功能:

1、計算computed屬性的值,進行緩存

2、執行computed的get方法時進行依賴收集,ComputedWatcher作爲監聽者被添加到data屬性或其它computed屬性的依賴管理數組中

3、模板解析識別出計算屬性後,調用addCall向ComputedWatcher添加監聽者

4、update方法獲執行computed計算方法調用,遍歷執行依賴數組的函數更新視圖

5、TemplateCompiler解析模板函數的修改

// 創建模板編譯工具
function TemplateCompiler(el,vm){
    this.el = this.isElementNode(el) ? el : document.querySelector(el);
    this.vm = vm;
    if (this.el) {
        //將對應範圍的html放入內存fragment
        var fragment = this.node2Fragment(this.el)
        //編譯模板
        this.compile(fragment)
        //將數據放回頁面
        this.el.appendChild(fragment)
      }
}

//是否是元素節點
TemplateCompiler.prototype.isElementNode=function(node){
    return node.nodeType===1
}

//是否是文本節點
TemplateCompiler.prototype.isTextNode=function(node){
    return node.nodeType===3
}

//轉成數組
TemplateCompiler.prototype.toArray=function(arr){
    return [].slice.call(arr)
}

//判斷是否是指令屬性
TemplateCompiler.prototype.isDirective=function(directiveName){
    return directiveName.indexOf('v-') >= 0;
}

//讀取dom到內存
TemplateCompiler.prototype.node2Fragment=function(node){
    var fragment=document.createDocumentFragment();
    var child;
    //while(child=node.firstChild)這行代碼,每次運行會把firstChild從node中取出,指導取出來是null就終止循環
    while(child=node.firstChild){
        fragment.appendChild(child)
    }
    return fragment;
}

//編譯模板
TemplateCompiler.prototype.compile=function(fragment){
    var childNodes = fragment.childNodes;
    var arr = this.toArray(childNodes);
    arr.forEach(node => {
        //判斷是否是元素節點
        if(this.isElementNode(node)){
            this.compileElement(node);
        }else{
            //定義文本表達式驗證規則
            var textReg = /\{\{(.+)\}\}/;
            var expr = node.textContent;
            if (textReg.test(expr)) {
                expr = RegExp.$1;
                //調用方法編譯
                this.compileText(node, expr)
            }
        }
    });
}

//解析元素節點
TemplateCompiler.prototype.compileElement=function(node){
    var arrs=node.attributes;
    this.toArray(arrs).forEach(attr => {
        var attrName=attr.name;
        if(this.isDirective(attrName)){
            //獲取v-text的text
            var type = attrName.split('-')[1]
            var expr = attr.value;
            CompilerUtils[type] && CompilerUtils[type](node, this.vm, expr)
        }  
    });
}

 //解析文本節點
 TemplateCompiler.prototype.compileText=function(node,expr){
    CompilerUtils.text(node, this.vm, expr)
}

CompilerUtils = {    
    /*******解析v-model指令時候只執行一次,但是裏面的更新數據方法會執行n多次*********/
    model(node, vm, expr) {
        if(vm.$data[expr]){
            var updateFn = this.updater.modelUpdater;
            updateFn && updateFn(node, vm.$data[expr])

            /*第n+1次 */
            new Watcher(vm, expr, (newValue) => {
                //發出訂閱時候,按照之前的規則,對節點進行更新
                updateFn && updateFn(node, newValue)
            })

            //視圖到模型(觀察者模式)
            node.addEventListener('input', (e) => {
            //獲取新值放到模型
            var newValue = e.target.value;
            vm.$data[expr] = newValue;
            })
        }
    },

    /*******解析v-text指令時候只執行一次,但是裏面的更新數據方法會執行n多次*********/
    text(node, vm, expr) {
        //判斷是否是data屬性
        if(vm.$data[expr]){
            /*第一次*/
            var updateFn = this.updater.textUpdater;
            updateFn && updateFn(node, vm.$data[expr])

            /*第n+1次 */
            new Watcher(vm, expr, (newValue) => {
                //發出訂閱時候,按照之前的規則,對節點進行更新
                updateFn && updateFn(node, newValue)
            })
        }
        //認爲是計算屬性
        else{
            this.textComputed(node,vm,expr)
        }
    },

    //新增text computed屬性的解析方法
    textComputed(node, vm, expr) {
        var updateFn = this.updater.textUpdater;
        //獲取當前屬性的監聽者
        let watcher=vm.$computedWatcherManage[expr];

        //第一次
        updateFn(node,vm.$computed[expr]);

        //添加更新View的回調方法
        watcher.addCall((value)=>{
            updateFn(node, value);
        })
    },

    updater: {
        //v-text數據回填
        textUpdater(node, value) {
          node.textContent = value;
        },
        //v-model數據回填
        modelUpdater(node, value) {
          node.value = value;
        }
    }
}

這個函數主要做了2點修改:

1、修改text方法,如果data裏不包含該屬性,當做計算屬性處理

2、新增textComputed方法,把該節點的更新函數添加到watcher的依賴數組

6、爲該框架增加一個簡易的計算屬性就完成了,下面看下運行效果:

iShot_2022-08-11_10.13.25

初始化的時候會輸出:fullName 1 fullNameAge 1 fullName 1

先解釋fullName 1爲什麼輸出2次?

fullName和fullNameAge都是計算屬性。

fullNameAge依賴於fullName,fullName依賴與data的屬性name

Index.html中有輸出了四個fullName計算屬性,實際fullName計算屬性只執行了一次計算,把值緩存了下來,剩餘3個直接取緩存的值。輸出第二個fullName 1是因爲fullNameAge依賴與fullName,需要把fullNameAge的監聽者添加到data的屬性name的依賴數組中,這樣name屬性有更新的時候會執行到fullNameAge的監聽函數。

ok,自己實現的這部門還有改進空間,有能力的朋友幫忙改進哈!不明白的朋友可以加好友一起交流。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章