Following a successful mutation to the vuex store (state.posts.post.comments
) with the use of this code snippet and implementing Vue.set
for Vue to acknowledge the addition of an object property:
store/modules/post.js
const mutations = {
[types.SET_POST_COMMENTS] (state, { comments, id }) {
let post = state.posts.find(post => post._id === id)
Vue.set(post, 'comments', comments)
}
}
Even though the Vuex store is correctly updated with a comments object for each post, the SinglePost.vue
component does not reflect these changes. The prop post
is non-reactive, suggesting that even the watcher is not being triggered.
SinglePost.vue
export default {
name: 'single-post',
props: {
'post': {
type: Object
}
},
data () {
return {
currPost: this.post // attempted to locally reassign post
}
},
computed: {
comments() {
return this.post.comments // tried to compute comments locally
}
},
watch: {
post: function(val) { // attempted to watch currPost for changes
console.log('never triggered')
this.currPost = val
}
}
One possible solution is to manually set a local variable by explicitly retrieving comments from the store in a component method and setting a local comments object, but I would prefer to utilize my centralized store (assuming there is a solution).
SinglePost template
{{comments}} // always empty
{{post}} // does not reflect Vue.set in the store for post.comments
{{currPost}} // does not reflect Vue.set in the store for post.comments
Edit
The method of obtaining posts is as follows:
getPosts ({ commit, state, getters, dispatch, rootState }, ctx) {
//other stuff
APIHelper.post('/post/search', mergedPayload).then(res => {
var results = res.data.results
commit('SET_POSTS', posts || [])
// where SET_POSTS simply assigns state.posts = posts
The vuex action getPosts
is triggered from the Posts.vue
component without returning anything, as it is handled by a mutation @click="getPosts(this.context)"
(this successfully sets the posts)
<div v-for="post in posts">
<single-post :key="post._id" :post="post" context="feed" />
</div>