Skip to content

Commit

Permalink
fix(computedEager): adapt to changes in vue3.4+ (#3689)
Browse files Browse the repository at this point in the history
  • Loading branch information
Doctor-wu committed Jan 3, 2024
1 parent 306c825 commit b6d8f1e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
5 changes: 5 additions & 0 deletions packages/shared/computedEager/index.md
Expand Up @@ -7,6 +7,11 @@ alias: eagerComputed

Eager computed without lazy evaluation.

::: tip
Note💡: If you are using Vue 3.4+, you can straight use `computed` instead. Because in Vue 3.4+, if computed new value does not change, `computed`, `effect`, `watch`, `watchEffect`, `render` dependencies will not be triggered.
Refer: https://github.com/vuejs/core/pull/5912
:::

Learn more at [Vue: When a computed property can be the wrong tool](https://dev.to/linusborg/vue-when-a-computed-property-can-be-the-wrong-tool-195j).

- Use `computed()` when you have a complex calculation going on, which can actually profit from caching and lazy evaluation and should only be (re-)calculated if really necessary.
Expand Down
6 changes: 4 additions & 2 deletions packages/shared/computedEager/index.test.ts
@@ -1,4 +1,4 @@
import { computed, ref, watch } from 'vue-demi'
import { computed, isVue3, ref, watch } from 'vue-demi'
import { describe, expect, it, vi } from 'vitest'
import { nextTwoTick } from '../../.test'
import { computedEager } from '.'
Expand Down Expand Up @@ -93,7 +93,9 @@ describe('computedEager', () => {
expect(isOddEagerComputed.value).toBe(true)
expect(isOddComputedSpy).toBeCalledTimes(1)
expect(isOddComputedRefSpy).toBeCalledTimes(1)
expect(isOddComputedCollectSpy).toBeCalledTimes(3)
// Since Vue 3.4, computed will not trigger collect change if result is not changed
// refer: https://github.com/vuejs/core/pull/5912
expect(isOddComputedCollectSpy).toBeCalledTimes(isVue3 ? 2 : 3)
expect(isOddComputedRefCollectSpy).toBeCalledTimes(2)
})
})
10 changes: 10 additions & 0 deletions packages/shared/computedEager/index.ts
Expand Up @@ -4,6 +4,16 @@
import type { Ref, WatchOptionsBase } from 'vue-demi'
import { readonly, shallowRef, watchEffect } from 'vue-demi'

/**
* Note: If you are using Vue 3.4+, you can straight use computed instead.
* Because in Vue 3.4+, if computed new value does not change,
* computed, effect, watch, watchEffect, render dependencies will not be triggered.
* refer: https://github.com/vuejs/core/pull/5912
*
* @param fn effect function
* @param options WatchOptionsBase
* @returns readonly ref
*/
export function computedEager<T>(fn: () => T, options?: WatchOptionsBase): Readonly<Ref<T>> {
const result = shallowRef()

Expand Down

0 comments on commit b6d8f1e

Please sign in to comment.