手写 computed
这里采用简单粗暴的方式,直接返回一个 effect
export function computed (getter) {
const result = ref()
// getter() 访问响应式对象属性,去收集依赖,并返回结果值赋值给 result.value
effect(() => (result.value = getter()))
return result
}
测试
<!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, computed } from './reactivity/index.js'
const product = reactive({
name: 'iPhone',
price: 5000,
count: 3
})
let total = computed(() => {
return product.price * product.count
})
console.log(total.value)
product.price = 4000
console.log(total.value)
product.count = 1
console.log(total.value)
</script>
</body>
</html>
打赏作者
您的打赏是我前进的动力
微信
支付宝
手写 toRefs
上一篇
评论