Skip to content

Commit

Permalink
fix: fix getters stop working when component is destroyed (#1884)
Browse files Browse the repository at this point in the history
  • Loading branch information
kiaking committed Nov 25, 2020
1 parent 46dfe9c commit c3a695e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
6 changes: 5 additions & 1 deletion docs/guide/getters.md
Expand Up @@ -14,7 +14,11 @@ computed: {

If more than one component needs to make use of this, we have to either duplicate the function, or extract it into a shared helper and import it in multiple places - both are less than ideal.

Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. Like computed properties, a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed.
Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores.

::: warning WARNING
As of Vue 3.0, the getter's result is **not cached** as the computed property does. This is a known issue that requires Vue 3.1 to be released. You can learn more at [PR #1878](https://github.com/vuejs/vuex/pull/1883).
:::

Getters will receive the state as their 1st argument:

Expand Down
8 changes: 4 additions & 4 deletions src/store.js
@@ -1,4 +1,4 @@
import { reactive, computed, watch } from 'vue'
import { reactive, watch } from 'vue'
import { storeKey } from './injectKey'
import devtoolPlugin from './plugins/devtool'
import ModuleCollection from './module/module-collection'
Expand Down Expand Up @@ -286,15 +286,15 @@ function resetStoreState (store, state, hot) {
store._makeLocalGettersCache = Object.create(null)
const wrappedGetters = store._wrappedGetters
const computedObj = {}
const computedCache = {}
forEachValue(wrappedGetters, (fn, key) => {
// use computed to leverage its lazy-caching mechanism
// direct inline function use will lead to closure preserving oldState.
// using partial to return function with only arguments preserved in closure environment.
computedObj[key] = partial(fn, store)
computedCache[key] = computed(() => computedObj[key]())
Object.defineProperty(store.getters, key, {
get: () => computedCache[key].value,
// TODO: use `computed` when it's possible. at the moment we can't due to
// https://github.com/vuejs/vuex/pull/1883
get: () => computedObj[key](),
enumerable: true // for local getters
})
})
Expand Down

0 comments on commit c3a695e

Please sign in to comment.