【筆記】Vue-6 - 實現set和數組響應式

Vue.set()

vue2.0中不能直接監聽對象中新增屬性的變化,若是須要監聽,須要經過 Vue.set( target, propertyName/index, value )方法添加html

set函數經過Object.defineProperty將傳入的對象上的屬性變爲響應式屬性,簡易版實現以下:vue

const set = (target, prop, initValue) => {
    let value = initValue
    let dep = new Dep()
    return Object.defineProperty(target, prop, {
      get() {
        dep.depend()
        return value
      },
      set(newValue) {
        value = newValue
        dep.notify()
      }
    })
  }

這段代碼中的邏輯與ref函數中的邏輯重複,將代碼提取放到createReactive函數中。api

數組響應式

Vue源碼中對於push pop shift unshift splice sort reverse這些方法進行了處理,使得經過這些方法操做數組時能感知到數據的變化。數組

處理數組原型上的push方法app

  1. 經過set生成一個響應式數組,在執行set函數時,已經添加了依賴
  2. 改造數組原型上的push方法。首先將原型上的push方法存儲起來,再從新定義Array.prototype.push。
  3. 在新方法中首先執行原本的push操做,而後須要調用notify方法,觸發依賴的執行。notify方法掛載在createReactive函數內的dep實例上,這裏的this即createReactive函數中的target對象,因此能夠改造createReactive函數,將dep實例掛載到target的_dep屬性上。這樣就能夠拿到並觸發notify了。
let createReactive = (target, prop, value) => {
    // let dep = new Dep()
    target._dep = new Dep()
    if (Array.isArray(target)) {
      target.__proto__ = arrayMethods
    }
    return Object.defineProperty(target, prop, {
      get() {
        target._dep.depend()
        return value
      },
      set(newValue) {
        value = newValue
        target._dep.notify()
      }
    })
  }
  
  let push = Array.prototype.push
  let arrayMethods = Object.create(Array.prototype)
  arrayMethods.push = function (...args) {
    push.apply(this, [...args])
    // 這裏須要調用notify方法
    // notify方法掛載在createReactive函數內的dep實例上,修改成掛載到target上
    // 這裏經過this就能夠拿到notify方法
    this._dep && this._dep.notify()
  }

完整帶示例代碼:異步

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="add">add</button>
  <div id="app"></div>
  <hr>
  <button id="addArr">addArr</button>
  <div id="appArr"></div>
</body>
<script>
  let active

  let effect = (fn, options = {}) => {
    // 爲何要增長一個_effect函數
    // 由於須要給_effect增長屬性
    // 也能夠直接給fn增長,可是因爲引用類型的緣由,會對fn函數形成污染
    let _effect = (...args) => {
      try {
        active = _effect
        return fn(...args)
      } finally {
        active = null
      }
    }

    _effect.options = options
    _effect.deps = [] // effect和dep的關係-1
    return _effect
  }

  let cleanUpEffect = (effect) => {
    // 清除依賴
    // 須要反向查找effect被哪些dep依賴了
    // 在effect上添加[] 創建雙向索引
    const { deps } = effect
    console.log(deps)
    console.log(effect)
    if (deps.length) {
      for (let i = 0; i < deps.length; i++) {
        deps[i].delete(effect)
      }
    }
  }

  let watchEffect = (cb) => {
    /* active = cb
    active()
    active = null */
    let runner = effect(cb)
    runner()

    return () => {
      cleanUpEffect(runner)
    }
  }

  let nextTick = (cb) => Promise.resolve().then(cb)

  // 隊列
  let queue = []

  // 添加隊列
  let queueJob = (job) => {
    if (!queue.includes(job)) {
      queue.push(job)
      // 添加以後,將執行放到異步任務中
      nextTick(flushJob)
    }
  }

  // 執行隊列
  let flushJob = () => {
    while (queue.length > 0) {
      let job = queue.shift()
      job && job()
    }
  }


  let Dep = class {
    constructor() {
      // 存放收集的active
      this.deps = new Set()
    }
    // 依賴收集
    depend() {
      if (active) {
        this.deps.add(active)
        active.deps.push(this.deps) // effect和dep的關係-2
      }
    }
    // 觸發
    notify() {
      this.deps.forEach(dep => queueJob(dep))
      this.deps.forEach(dep => {
        dep.options && dep.options.schedular && dep.options.schedular()
      })
    }
  }

  let createReactive = (target, prop, value) => {
    // let dep = new Dep()
    target._dep = new Dep()
    if (Array.isArray(target)) {
      target.__proto__ = arrayMethods
    }
    return Object.defineProperty(target, prop, {
      get() {
        target._dep.depend()
        return value
      },
      set(newValue) {
        value = newValue
        target._dep.notify()
      }
    })
  }

  let ref = (initValue) => createReactive({}, 'value', initValue)

  const set = (target, prop, initValue) => createReactive(target, prop, initValue)

  let computed = (fn) => {
    let value
    let dirty = true // 爲true代表依賴的變量發生了變化,此時須要從新計算
    let runner = effect(fn, {
      schedular() {
        if (!dirty) {
          dirty = true
        }
      }
    })
    return {
      get value() {
        if (dirty) {
          // 什麼時候將dirty重置爲true,當執行fn後
          // 所以須要經過配置回調函數,在執行fn後將dirty重置爲true
          // value = fn() 
          value = runner()
          dirty = false
        }
        return value
      }
    }
  }

  let watch = (source, cb, options = {}) => {
    const { immediate } = options
    const getter = () => {
      return source()
    }
    // 將函數添加到count的依賴上去,當count變化時
    let oldValue
    const runner = effect(getter, {
      schedular: () => applyCb()
    })

    const applyCb = () => {
      let newValue = runner()
      if (newValue !== oldValue) {
        cb(newValue, oldValue)
        oldValue = newValue
      }
    }

    if (immediate) {
      applyCb()
    } else {
      oldValue = runner()
    }
  }

  let push = Array.prototype.push
  let arrayMethods = Object.create(Array.prototype)

  arrayMethods.push = function (...args) {
    console.log(this)
    push.apply(this, [...args])
    // 這裏須要調用notify方法
    // notify方法掛載在createReactive函數內的dep實例上,修改成掛載到target上
    // 這裏經過this就能夠拿到notify方法
    this._dep && this._dep.notify()
  }

  // set示例:
  let count = ref(0)
  /* // count.v新增屬性,不會有響應式變化
  document.getElementById('add').addEventListener('click', function () {
    if (!count.v) {
      count.v = 0
    }
    count.v++
  })

  let str
  let stop = watchEffect(() => {
    str = `hello ${count.v}`
    document.getElementById('app').innerText = str
  }) */

  document.getElementById('add').addEventListener('click', function () {
    if (!count.v) {
      set(count, 'v', 0)
      watchEffect(() => {
        str = `hello ${count.v}`
        document.getElementById('app').innerText = str
      })
    }
    count.v++
  })

  // 數組push示例:
  let arrValue = 0
  // set函數中已經對依賴進行了一次添加
  let countArr = set([], 1, 0)
  document.getElementById('addArr').addEventListener('click', function () {
    arrValue++
    countArr.push(arrValue)
  })
  watchEffect(() => {
    str = `hello ${countArr.join(',')}`
    document.getElementById('appArr').innerText = str
  })

</script>

</html>
相關文章
相關標籤/搜索