往期内容:
《Vue零基础入门教程》合集(完结)
《Vue进阶教程》第一课:什么是组合式API
《Vue进阶教程》第二课:为什么提出组合式API
《Vue进阶教程》第三课:Vue响应式原理
《Vue进阶教程》第四课:reactive()函数详解
《Vue进阶教程》第五课:ref()函数详解(重点)
《Vue进阶教程》第六课:computed()函数详解(上)
4) 基于effect实现computed
基本实现
从computed()函数的使用上分析
computed()函数的参数是一个副作用函数, 依赖响应式对象
computed()函数跟注册副作用函数effect()类似. 接收一个副作用函数
做为参数
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><script src="../node_modules/vue/dist/vue.global.js"></script></head><body><script>const { ref, effect } = Vuefunction computed(fn) {// 只考虑参数是fn的情况const run = effect(fn)return {get value() {return run()},}}const firstname = ref('xiao')const lastname = ref('ming')const fullname = computed(() => {console.log('副作用函数被执行了...')return firstname.value + lastname.value})</script></body>
</html>
实现懒执行
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><script src="../node_modules/vue/dist/vue.global.js"></script></head><body><script>const { ref, effect } = Vuefunction computed(fn) {// 只考虑参数是fn的情况const run = effect(fn, { lazy: true })return {get value() {return run()},}}const firstname = ref('xiao')const lastname = ref('ming')const fullname = computed(() => {console.log('副作用函数被执行了, 值是:',firstname.value + lastname.value)return firstname.value + lastname.value})</script></body>
</html>
实现缓存
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><script src="../node_modules/vue/dist/vue.global.js"></script></head><body><script>const { ref, effect } = Vuefunction computed(fn) {let cachelet dirty = true// 只考虑参数是fn的情况const run = effect(fn, {lazy: true,shecduler: () => {dirty = true},})return {get value() {if (dirty) {cache = run()dirty = false}return cache},}}const firstname = ref('xiao')const lastname = ref('ming')const fullname = computed(() => {console.log('副作用函数被执行了, 值是:',firstname.value + lastname.value)return firstname.value + lastname.value})</script></body>
</html>