Przeglądaj źródła

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

Kia King Ishii 4 lat temu
rodzic
commit
c3a695e106
2 zmienionych plików z 9 dodań i 5 usunięć
  1. 5 1
      docs/guide/getters.md
  2. 4 4
      src/store.js

+ 5 - 1
docs/guide/getters.md

@@ -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:
 

+ 4 - 4
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'
@@ -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
     })
   })