1

Vue3.0 响应式由 Object.defineProperty 改为 Proxy 实现
因为前者无法监听到对象上增删属性的变化

Vue3.0的响应式用到了Proxy和Reflect两个ES6新增的功能

Proxy

Proxy 可以理解成,在目标对象之前架设一层“拦截”,外界对该对象的访问,都必须先通过这层拦截,因此提供了一种机制,可以对外界的访问进行过滤和改写。

Reflect

Reflect对象与Proxy对象一样,也是 ES6 为了操作对象而提供的新 API。Reflect对象的设计目的有这样几个。

  1. Object对象的一些明显属于语言内部的方法(比如Object.defineProperty),放到Reflect对象上。
  2. 修改某些Object方法的返回结果,让其变得更合理。比如,Object.defineProperty(obj, name, desc)在无法定义属性时,会抛出一个错误,而Reflect.defineProperty(obj, name, desc)则会返回false
  • Reflect.get(target, name, receiver)
    Reflect.get方法查找并返回target对象的name属性,如果没有该属性,则返回undefined
  • Reflect.set(target, name, value, receiver)
    Reflect.set方法设置target对象的name属性等于value

createReactive函数中改为使用Proxy

let createReactive = (target, prop, value) => {
    target._dep = new Dep()
    return new Proxy(target, {
      get(target, prop) {
        target._dep.depend()
        return Reflect.get(target, prop)
      },
      set(target, prop, value) {
        target._dep.notify()
        return Reflect.set(target, prop, value)
      }
    })
  }

示例:

  1. 直接监听对象新增的属性
  2. 去掉push方法的处理,直接使用

都可以成功

<!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) => {
    target._dep = new Dep()
    return new Proxy(target, {
      get(target, prop) {
        target._dep.depend()
        return Reflect.get(target, prop)
      },
      set(target, prop, value) {
        target._dep.notify()
        return Reflect.set(target, prop, value)
      }
    })
  }

  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()
    }
  }

  // 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
  })

  // 数组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>

CSep27
37 声望1 粉丝

学习中...整理中...