vuex存储更改时更新prop属性

时间:2018-02-06 19:40:00

标签: javascript vue.js vuex

使用此代码成功突变到vuex商店(state.posts.post.comments)并使用Vue.set后,Vue可以识别添加对象属性:

商品/模块/ 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)
    }
}

模板或组件没有更新。道具post是非反应性的(我假设因为即使观察者也没有被触发)。我已经仔细检查了每个帖子的评论属性的Vuex商店是否已成功使用评论对象进行更新,但组件SinglePost.vue没有看到这些更改。

SinglePost.vue

export default {
  name: 'single-post',
  props: {
    'post': {
      type: Object
    }
  },
  data () {
    return {
      currPost: this.post // tried to reassign post locally
    }
  },
  computed: {
    comments() {
      return this.post.comments // tried to compute comments locally
    }
  },
  watch: {
    post: function(val) { // tried to watch currPost for changes
       console.log('never triggered')
       this.currPost = val 
    }
  }

最终,我可以通过显式地将商店中的注释返回到组件方法并设置本地注释对象来设置本地var,但我想使用我的中央存储(并假设有一种方法)。 / p>

SinglePost模板

{{comments}} // always empty
{{post}} // doesn't reflect store Vue.set for post.comments
{{currPost}} // doesn't reflect store Vue.set for post.comments

修改

我如何获得帖子:

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 is just state.posts = posts

vuex操作getPostsPosts.vue组件调用而不返回任何内容,因为它是由变异@click="getPosts(this.context)"设置的(这非常适合设置帖子)

    <div v-for="post in posts">
      <single-post :key="post._id" :post="post" context="feed" />
    </div>

2 个答案:

答案 0 :(得分:2)

您应该使用vuex&#39; mapGetters helper method

computed: {
    ...mapGetters({
        currPost: 'GET_CURRENT_POST'
    })
},

它可以访问商店状态并且具有反应性,因此您不需要观察者或其他计算器。

答案 1 :(得分:0)

双向数据绑定是实现此目的的好方法,您可以创建自己的getter / setter方法,并在需要时将其导入Vue组件中:

export function mapFields(fields)
{
    let computers = {}
    for (let field of fields) {
        computers[field] = {
            get() {
                return this.$store.state[field];
            },
            set(value) {
                this.$store.commit(`UPDATE_${field.toUpperCase()}`, value);
            }
        }
    }
    return computers;
}

然后在您的Vue组件中:

import {mapFields} from 'utils.js'; // or whatever the name of the file

computed: {
   ...mapFields(['mappedState']),
},

在Vue组件中更新this.mappedState:

this.mappedState = ['foo', 'bar'];

将触发:

this.$store.commit('UPDATE_MAPPEDSTATE', ['foo', 'bar']);

要获取属性的数据,只需在您的组件中调用它即可:

// In your template
{{ mappedState }}

// In Vue methods
this.mappedState;
相关问题