1
- import { reactive , watch } from 'vue'
1
+ import { reactive , computed , watch , effectScope } from 'vue'
2
2
import { forEachValue , isObject , isPromise , assert , partial } from './util'
3
3
4
4
export function genericSubscribe ( fn , subs , options ) {
@@ -29,30 +29,42 @@ export function resetStore (store, hot) {
29
29
30
30
export function resetStoreState ( store , state , hot ) {
31
31
const oldState = store . _state
32
+ const oldScope = store . _scope
32
33
33
34
// bind store public getters
34
35
store . getters = { }
35
36
// reset local getters cache
36
37
store . _makeLocalGettersCache = Object . create ( null )
37
38
const wrappedGetters = store . _wrappedGetters
38
39
const computedObj = { }
39
- forEachValue ( wrappedGetters , ( fn , key ) => {
40
- // use computed to leverage its lazy-caching mechanism
41
- // direct inline function use will lead to closure preserving oldState.
42
- // using partial to return function with only arguments preserved in closure environment.
43
- computedObj [ key ] = partial ( fn , store )
44
- Object . defineProperty ( store . getters , key , {
45
- // TODO: use `computed` when it's possible. at the moment we can't due to
46
- // https://github.com/vuejs/vuex/pull/1883
47
- get : ( ) => computedObj [ key ] ( ) ,
48
- enumerable : true // for local getters
40
+ const computedCache = { }
41
+
42
+ // create a new effect scope and create computed object inside it to avoid
43
+ // getters (computed) getting destroyed on component unmount.
44
+ const scope = effectScope ( true )
45
+
46
+ scope . run ( ( ) => {
47
+ forEachValue ( wrappedGetters , ( fn , key ) => {
48
+ // use computed to leverage its lazy-caching mechanism
49
+ // direct inline function use will lead to closure preserving oldState.
50
+ // using partial to return function with only arguments preserved in closure environment.
51
+ computedObj [ key ] = partial ( fn , store )
52
+ computedCache [ key ] = computed ( ( ) => computedObj [ key ] ( ) )
53
+ Object . defineProperty ( store . getters , key , {
54
+ get : ( ) => computedCache [ key ] . value ,
55
+ enumerable : true // for local getters
56
+ } )
49
57
} )
50
58
} )
51
59
52
60
store . _state = reactive ( {
53
61
data : state
54
62
} )
55
63
64
+ // register the newly created effect scope to the store so that we can
65
+ // dispose the effects when this method runs again in the future.
66
+ store . _scope = scope
67
+
56
68
// enable strict mode for new state
57
69
if ( store . strict ) {
58
70
enableStrictMode ( store )
@@ -67,6 +79,11 @@ export function resetStoreState (store, state, hot) {
67
79
} )
68
80
}
69
81
}
82
+
83
+ // dispose previously registered effect scope if there is one.
84
+ if ( oldScope ) {
85
+ oldScope . stop ( )
86
+ }
70
87
}
71
88
72
89
export function installModule ( store , rootState , path , module , hot ) {
0 commit comments