In the official documentation of Vue3, there is this description of computed properties:
For any response containing For complex logic of formula data, we should use calculated properties.
Computed properties will only be re-evaluated when the related reactive dependency changes.
From the above description, the requirements for calculated attributes can be clearly understood. Computed attributes calculate responsive data (satisfying description 1), and the calculation results should be cached (satisfying description 2) ). Let's implement it one by one, first using computed
to create a computed property.
function effect(fn) { // 副作用函数 const effectFn = () => { cleanup(effectFn) activeEffect = effectFn effectStack.push(effectFn) fn() effectStack.pop() activeEffect = effectStack[effectStack.length - 1] } effectFn.deps = [] effectFn() } ... const data = { foo: 1, bar: 2 } const obj = new Proxy(data, { // 响应式对象 get(target, key) { track(target, key) return target[key] }, set(target, key, newValue) { target[key] = newValue trigger(target, key) return true } }) ... const sumRes = computed(() => obj.foo + obj.bar) // (1) console.log(sumRes.value)
At (1), we simply wrote a function to calculate the attribute. In order to realize the function of reading the calculated attribute value through sumRes.value
, when implementing the calculated attribute, we need to return An object that triggers side effect functions through get
within the object.
function computed(getter) { const effectFn = effect(getter) const obj = { get value() { return effectFn() } } return obj }
But this function obviously cannot be executed. This is because when we implemented effect
earlier, we needed to directly execute the side effect function without providing a return value. Without a return value, computed
naturally cannot obtain the execution result of effect
. Therefore, when using effect
in a calculated property, the side effect function needs to be returned to the calculated property, and the calculated property determines when to execute it, instead of being executed immediately by effect
(i.e. Lazy execution).
In order to achieve this, we need to add a switch lazy
to effect
, considering that we may need to configure other effect
in the future Features, we use an object options
to encapsulate this switch.
function effect(fn, options = {}) { const effectFn = () => { cleanup(effectFn) activeEffect = effectFn effectStack.push(effectFn) const res = fn() // (1) effectStack.pop() activeEffect = effectStack[effectStack.length - 1] return res // (2) } effectFn.deps = [] effectFn.options = options // (3) if (!options.lazy) { // (4) effectFn() } return effectFn // (5) }
We placed the lazy
switch at (4), and side effect functions that do not require lazy execution will also be automatically executed. The result of the side effect function is returned at (1) (2) (5) for lazy execution. At the same time, options
is passed down at (3) to ensure that when nesting of effect
occurs, the side effect function will also perform the expected behavior. Based on the above effect
modifications, we set the lazy
switch in computed
.
function computed(getter) { const effectFn = effect(getter, { lazy: true }) const obj = { get value() { // (6) return effectFn() } } return obj } const sumRes = computed(() => obj.foo + obj.bar)
As can be seen from the above figure, we have implemented description 1, that is, using calculated properties to calculate responsive data, when the value of the responsive data changes , the value of the calculated attribute will also change accordingly. But observing point (6) of the above code, it is not difficult to find that no matter what the situation, as long as the value of sumRes.value
is read, a side effect function will be triggered, causing it to redo the possibly unnecessary implement. So next, we try to implement description 2, caching the results of the calculated attribute.
Let’s start with the simplest one. We use a variable value
to cache the last calculated value, and add a dirty
switch to record whether the side effects need to be retriggered. function.
function computed(getter) { let value let dirty = true const effectFn = effect(getter, { lazy: true }) const obj = { get value() { if(dirty) { value = effectFn() dirty = false } return value } } return obj }
After modification, the cached value will take effect. But this creates an obvious BUG. When the value of dirty
is set to false
, it can no longer be changed to true
, which means, No matter how the responsive data obj.bar
and obj.foo
change, the value of the calculated attribute can always be the cached value value
, as shown in the figure below .
In order to solve this problem, we need a way to change the value of obj.bar
or obj.foo
When, before obtaining sumRes.value
, set the value of the dirty
switch to true
. Inspired by the previous lazy loading, we tried to see if we could achieve this function by configuring options
.
const obj = new Proxy(data, { get(target, key) { track(target, key) return target[key] }, set(target, key, newValue) { target[key] = newValue trigger(target, key) return true } })
Let’s recall the entire process of the responsive object. When the data in the responsive object is modified, trigger
is executed to trigger the collected side effect function. In computed properties, we no longer need to automatically trigger side-effect functions. So it is natural to think, can I set dirty
to true
in this place? Following this idea, we first modify trigger
.
function trigger(target, key) { const propsMap = objsMap.get(target) if(!propsMap) return const fns = propsMap.get(key) const otherFns = new Set() fns && fns.forEach(fn => { if(fn !== activeEffect) { otherFns.add(fn) } }) otherFns.forEach(fn => { if(fn.options.scheduler) { // (7) fn.options.scheduler() } else { fn() } }) }
According to the previous idea, we added a judgment at (7), if the configuration item options
of the side effect function fn
contains scheduler
function, we will execute scheduler
instead of the side effect function fn
. We call scheduler
here scheduler. Correspondingly, we add the scheduler in the calculated attribute.
function computed(getter) { let value let dirty = true const effectFn = effect(getter, { lazy: true, scheduler() { // (8) dirty = true } }) const obj = { get value() { if(dirty) { value = effectFn() dirty = false } return value } } return obj }
在(8)处我们添加了调度器。添加调度器后,让我们再来串一下整个流程,当响应式数据被修改时,才会执行trigger
函数。由于我们传入了调度器,因此trigger
函数在执行时不再触发副作用函数,转而执行调度器,此时dirty
开关的值变为了true
。当程序再往下执行时,由于dirty
已经变为true
,副作用函数就可以正常被手动触发。效果如下图所示。
到这里为止,计算属性在功能上已经实现完毕了,让我们尝试完善它。在Vue中,当计算属性中的响应式数据被修改时,计算属性值会同步更改,进而重新渲染,并在页面上更新。渲染函数也会执行effect
,为了说明问题,让我们使用effect
简单的模拟一下。
const sumRes = computed(() => obj.foo + obj.bar) effect(() => console.log('sumRes =', sumRes.value))
这里我们的预期是当obj.foo
或obj.bar
改变时,effect
会自动重新执行。这里存在的问题是,正常的effect
嵌套可以被自动触发(这点我们在上一篇博客中已经实现了),但sumRes
包含的effect
仅会在被读取value
时才会被get
触发执行,这就导致响应式数据obj.foo
与obj.bar
无法收集到外部的effect
,收集不到的副作用函数,自然无法被自动触发。
function computed(getter) { let value let dirty = true const effectFn = effect(getter, { lazy: true, scheduler() { dirty = true trigger(obj, 'value') // (9) } }) const obj = { get value() { if(dirty) { value = effectFn() dirty = false } track(obj, 'value') // (10) return value } } return obj }
在(10)处我们手动收集了副作用函数,并当响应式数据被修改时,触发它们。
在设计调度器时,我们忽略了一个潜在的问题。
还是先来看一个例子:
effect(() => console.log(obj.foo)) for(let i = 0; i < 1e5; i++) { obj.foo++ }
随着响应式数据obj.foo
被不停修改,副作用函数也被不断重复执行,在明显的延迟之后,控制台打印出了大量的数据。但在前端的实际开发中,我们往往只关心最终结果,拿到结果显示在页面上。在这种条件下,我们如何避免副作用函数被重复执行呢?
const jobQueue = new Set() // (11) const p = Promise.resolve() // (12) let isFlushing = false // (13) function flushJob() { // (14) if (isFlushing) return isFlushing = true p.then(() => { jobQueue.forEach(job => { job() }) }).finally(() => { isFlushing = false }) }
这里我们的思路是使用微任务队列来进行优化。(11)处我们定义了一个Set
作为任务队列,(12)处我们定义了一个Promise
来使用微任务。精彩的部分来了,我们的思路是将副作用函数放入任务队列中,由于任务队列是基于Set
实现的,因此,重复的副作用函数仅会保留一个,这是第一点。接着,我们执行flushJob()
,这里我们巧妙的设置了一个isFlushing
开关,这个开关保证了被微任务包裹的任务队列在一次事件循环中只会执行一次,而执行的这一次会在宏任务完成之后触发任务队列中所有不重复的副作用函数,从而直接拿到最终结果,这是第二点。按照这个思路,我们在effect
中添加调度器。
effect(() => { console.log(obj.foo) }, { scheduler(fn) { jobQueue.add(fn) flushJob() } })
需要注意的是,浏览器在执行微任务时,会依次处理微任务队列中的所有微任务。因此,微任务在执行时会阻塞页面的渲染。因此,在实践中需避免在微任务队列中放置过于繁重的任务,以免导致性能问题。
The above is the detailed content of How to implement Vue3 calculated properties. For more information, please follow other related articles on the PHP Chinese website!