溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何解析Vue3的響應(yīng)式原理

發(fā)布時(shí)間:2021-12-15 16:29:33 來源:億速云 閱讀:183 作者:柒染 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)如何解析Vue3的響應(yīng)式原理,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

    Vue2響應(yīng)式原理回顧

    // 1.對(duì)象響應(yīng)化:遍歷每個(gè)key,定義getter、setter
    // 2.數(shù)組響應(yīng)化:覆蓋數(shù)組原型方法,額外增加通知邏輯
    const originalProto = Array.prototype
    const arrayProto = Object.create(originalProto)
      ;['push', 'pop', 'shift', 'unshift', 'splice', 'reverse', 'sort'].forEach(
        method => {
          arrayProto[method] = function () {
            originalProto[method].apply(this, arguments)
            notifyUpdate()
          }
        }
      )
    function observe (obj) {
      if (typeof obj !== 'object' || obj == null) {
        return
      }
      // 增加數(shù)組類型判斷,若是數(shù)組則覆蓋其原型
      if (Array.isArray(obj)) {
        Object.setPrototypeOf(obj, arrayProto)
      } else {
        const keys = Object.keys(obj)
        for (let i = 0; i < keys.length; i++) {
          const key = keys[i]
          defineReactive(obj, key, obj[key])
        }
      }
    }
    function defineReactive (obj, key, val) {
      observe(val) // 解決嵌套對(duì)象問題
      Object.defineProperty(obj, key, {
        get () {
          return val
        },
        set (newVal) {
          if (newVal !== val) {
            observe(newVal) // 新值是對(duì)象的情況
            val = newVal
            notifyUpdate()
          }
        }
      })
    }
    function notifyUpdate () {
      console.log('頁面更新!')
    }

    vue2響應(yīng)式弊端:
    響應(yīng)化過程需要遞歸遍歷,消耗較大
    新加或刪除屬性無法監(jiān)聽
    數(shù)組響應(yīng)化需要額外實(shí)現(xiàn)
    Map、Set、Class等無法響應(yīng)式
    修改語法有限制

    Vue3響應(yīng)式原理剖析

    vue3使用ES6的Proxy特性來解決這些問題。

    function reactive (obj) {
      if (typeof obj !== 'object' && obj != null) {
        return obj
      }
      // Proxy相當(dāng)于在對(duì)象外層加攔截
      // http://es6.ruanyifeng.com/#docs/proxy
      const observed = new Proxy(obj, {
        get (target, key, receiver) {
          // Reflect用于執(zhí)行對(duì)象默認(rèn)操作,更規(guī)范、更友好
          // Proxy和Object的方法Reflect都有對(duì)應(yīng)
          // http://es6.ruanyifeng.com/#docs/reflect
          const res = Reflect.get(target, key, receiver)
          console.log(`獲取${key}:${res}`)
          return res
        },
        set (target, key, value, receiver) {
          const res = Reflect.set(target, key, value, receiver)
          console.log(`設(shè)置${key}:${value}`)
          return res
        },
        deleteProperty (target, key) {
          const res = Reflect.deleteProperty(target, key)
          console.log(`刪除${key}:${res}`)
          return res
        }
      })
      return observed
    }
    //代碼測(cè)試
    const state = reactive({
      foo: 'foo',
      bar: { a: 1 }
    })
    // 1.獲取
    state.foo // ok
    // 2.設(shè)置已存在屬性
    state.foo = 'fooooooo' // ok
    // 3.設(shè)置不存在屬性
    state.dong = 'dong' // ok
    // 4.刪除屬性
    delete state.dong // ok

    嵌套對(duì)象響應(yīng)式

    測(cè)試:嵌套對(duì)象不能響應(yīng)

    // 設(shè)置嵌套對(duì)象屬性
    react.bar.a = 10 // no ok

    添加對(duì)象類型遞歸

      // 提取幫助方法
          const isObject = val => val !== null && typeof val === 'object'
          function reactive (obj) {
            //判斷是否對(duì)象
            if (!isObject(obj)) {
              return obj
            }
            const observed = new Proxy(obj, {
              get (target, key, receiver) {
                // ...
                // 如果是對(duì)象需要遞歸
                return isObject(res) ? reactive(res) : res
              },
              //...
            }

    避免重復(fù)代理

    重復(fù)代理,比如

    reactive(data) // 已代理過的純對(duì)象
    reactive(react) // 代理對(duì)象

    解決方式:將之前代理結(jié)果緩存,get時(shí)直接使用

    const toProxy = new WeakMap() // 形如obj:observed
          const toRaw = new WeakMap() // 形如observed:obj
          function reactive (obj) {
            //...
            // 查找緩存,避免重復(fù)代理
            if (toProxy.has(obj)) {
              return toProxy.get(obj)
            }
            if (toRaw.has(obj)) {
              return obj
            }
            const observed = new Proxy(...)
            // 緩存代理結(jié)果
            toProxy.set(obj, observed)
            toRaw.set(observed, obj)
            return observed
          }
          // 測(cè)試效果
          console.log(reactive(data) === state)
          console.log(reactive(state) === state)

    以上就是如何解析Vue3的響應(yīng)式原理,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    vue
    AI