Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix getters stop working when component is destroyed #1884

Merged
merged 1 commit into from
Nov 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/guide/getters.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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