我正在修改Vuex.store中对象数组中对象的现有属性的值。当我更新商店时,它不会触发重新呈现正在访问商店的计算属性。如果我将存储的值重置为空数组,然后再将其设置为我的新数组,它将触发更改。但只是更新对象数组的属性不会触发更改。
我已尝试使用Vue.set()
like the docs talk about,并更新商店,但仍未触发重新呈现计算属性。我错过了什么?使用Vue 2.2.4和Vuex 2.2.0。
//DEBUG: An example of the updated post I'm adding
let myNewScheduledPost = {
id: 1,
name: 'James'
};
this.$store.dispatch('addScheduledPost', post);
//DEBUG: My store
const options = {
state: {
scheduledPosts: [
{ id: 1, name: 'Jimmy'}
],
},
mutations: {
scheduledPosts: (state, scheduledPosts) => {
//This triggers the reactivity/change so my computed property re-renders
//But of course seems the wrong way to do it.
state.scheduledPosts = [];
state.scheduledPosts = scheduledPosts;
//Neither of these two lines triggers my computed property to re-render, even though there is a change in scheduledPosts
state.scheduledPosts = scheduledPosts;
Vue.set(state, 'scheduledPosts', scheduledPosts);
},
},
actions: {
addScheduledPost({ commit, getters }, newScheduledPost) {
let scheduledPosts = getters.scheduledPosts;
const idx = scheduledPosts.findIndex(existingScheduledPost => existingScheduledPost.id === newScheduledPost.id);
//If the post is already in our list, update that post
if (idx > -1) {
scheduledPosts[idx] = newScheduledPost;
} else {
//Otherwise, create a new one
scheduledPosts.push(newScheduledPost);
}
commit('scheduledPosts', scheduledPosts);
//DEBUG: This DOES have the correct updated change - but my component does not see the change/reactivity.
console.log(getters.scheduledPosts);
}
},
getters: {
scheduledPosts: (state) => {
return state.scheduledPosts;
}
}
};
//DEBUG: Inside of my component
computed: {
mySortedPosts()
{
console.log('im being re-rendered!');
return this.$store.getters.scheduledPosts.sort(function() {
//my sorted function
});
}
}
答案 0 :(得分:0)
如果您想访问不使用getter https://vuex.vuejs.org/en/state.html的州的一部分,则问题在于此。
computed: {
mySortedPosts(){
return this.$store.state.scheduledPosts
}
}
Getters用于商店中的计算属性 https://vuex.vuejs.org/en/getters.html。因此,在您的情况下,您可以创建一个getter来对您的预定帖子进行排序,然后将其命名为sortedScheduledPosts
,然后您可以像现在一样将它添加到组件计算属性中。
关键是你的getter需要一个与你的状态属性不同的名字,就像你在组件中一样。