手写 toRefs

export function toRefs (proxy) {
  // 判断 proxy 是不是 reactive 创建的对象
  const ret = proxy instanceof Array ? new Array(proxy.length) : {}
  // 若不是 reactive 创建的对象,发出警告(由于没有在 reactive 做出标识,此处先省略)

  for (const key in proxy) {
    // 将每一个属性都转成 ref 创建的对象
    ret[key] = toProxyRef(proxy, key)
  }

  return ret
}

function toProxyRef (proxy, key) {
  const r = {
    __v_isRef: true,
    get value () {
      // 会调用 proxy 中的 get,收集依赖(proxy 是 reactive 创建的对象)
      return proxy[key]
    },
    set value (newValue) {
      // 会调用 proxy 中的 set,触发更新(proxy 是 reactive 创建的对象)
      proxy[key] = newValue
    }
  }
  return r
}

测试

<!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>
  <script type="module">
    import { reactive, effect, toRefs } from './reactivity/index.js'
    function useProduct () {
      const product = reactive({
        name: 'iPhone',
        price: 5000,
        count: 3
      })
      
      return toRefs(product)
    }
    const { price, count } = useProduct()

    let total = 0 
    effect(() => {
      total = price.value * count.value
    })
    console.log(total)

    price.value = 4000
    console.log(total)

    count.value = 1
    console.log(total)
  </script>
</body>
</html>
打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. 手写 toRefs
  2. 2. 测试