Vuex,计算属性不是反应性的
Vuex, computed properties are not reactive
我试图在某些组件(子组件)之间共享一个状态,其中每个子组件(和父组件)都可以更新共享的 属性(存储在 vueX 状态中)。
我在这里做了一个小"How to reproduce":
Vue.component('urlQueryComponent', {
template: '<div>object: {{pathQuery}}</div>',
computed: {
pathQuery () {
return this.$store.state.urlQuery;
}
}
})
https://codepen.io/anon/pen/rvmLrZ?editors=1010
问题是当我在子组件中更新状态时,更改没有被处理。
VueX 实例:
const store = new Vuex.Store({
state: {
urlQuery: {
path: '',
query: {}
}
},
mutations: {
pushQuery: (state, type) => {
state.urlQuery.query[type.key] = type.value;
console.log('urlQuery: ', state.urlQuery);
},
pushPath: (state, path) => {
state.urlQuery.path = path;
}
},
getters: {
getUrlQuery: state => state.urlQuery
}
})
和父组件:
new Vue({
el: '#app',
store,
methods: {
changeType (type) {
this.$store.commit('changeType', type);
}
}
})
编辑:
经过反思,之前的代码并没有真正针对我的问题。 This fiddle 更针对我的问题。
将您的 pushQuery
突变更改为:
pushQuery: ({ urlQuery }, type) => {
const key = type.key
Vue.set(urlQuery.query, key, type.value)
console.log('urlQuery: ', urlQuery);
}
它应该有效 (fiddle here)
来源 (Vuex mutations) :
Mutations Follow Vue's Reactivity Rules
Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue:
Prefer initializing your store's initial state with all desired fields upfront.
When adding new properties to an Object, you should either use : Vue.set(obj, 'newProp', 123)
我试图在某些组件(子组件)之间共享一个状态,其中每个子组件(和父组件)都可以更新共享的 属性(存储在 vueX 状态中)。
我在这里做了一个小"How to reproduce":
Vue.component('urlQueryComponent', {
template: '<div>object: {{pathQuery}}</div>',
computed: {
pathQuery () {
return this.$store.state.urlQuery;
}
}
})
https://codepen.io/anon/pen/rvmLrZ?editors=1010
问题是当我在子组件中更新状态时,更改没有被处理。
VueX 实例:
const store = new Vuex.Store({
state: {
urlQuery: {
path: '',
query: {}
}
},
mutations: {
pushQuery: (state, type) => {
state.urlQuery.query[type.key] = type.value;
console.log('urlQuery: ', state.urlQuery);
},
pushPath: (state, path) => {
state.urlQuery.path = path;
}
},
getters: {
getUrlQuery: state => state.urlQuery
}
})
和父组件:
new Vue({
el: '#app',
store,
methods: {
changeType (type) {
this.$store.commit('changeType', type);
}
}
})
编辑:
经过反思,之前的代码并没有真正针对我的问题。 This fiddle 更针对我的问题。
将您的 pushQuery
突变更改为:
pushQuery: ({ urlQuery }, type) => {
const key = type.key
Vue.set(urlQuery.query, key, type.value)
console.log('urlQuery: ', urlQuery);
}
它应该有效 (fiddle here)
来源 (Vuex mutations) :
Mutations Follow Vue's Reactivity Rules Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue:
Prefer initializing your store's initial state with all desired fields upfront.
When adding new properties to an Object, you should either use :
Vue.set(obj, 'newProp', 123)