如何以非动态方式使用Vuex存储集合?

时间:2017-03-10 04:13:52

标签: redux vue.js vuejs2 vuex

new Vuex.Store({
   state: {
     comments: {
         //store comments collection of each article 
         /* articleId: [...commentsCollection] */
     },
     articles: {
       ids: [],
       collection: []
     }
   },
   mutations: {
     //add a comment to comments collection of an article
     ADD_COMMENT(state, comment){
       state.comments[comment.articleId].push(comment);
       //I'm not sure if below line is needed (it works without it tho)
       Vue.set(state.comments, comment.articleId, state.comments[comment.articleId]);
     }
   }
});
  • 我的第一个问题是如何在不使用Vue.set的情况下变异对象(这里)?
  • 其次,当我们在更新特定文章评论的comments(){ return this.$store.comments[this.articleId]; }状态时,使用comments等计算属性观察每篇文章中的评论时,其他文章的评论是否也会更新?如果是这样的情况不是很糟糕的实施?

  • 最后是否有更好的方式存储评论?

谢谢!

2 个答案:

答案 0 :(得分:1)

1)您不需要Vue.set,因为push方法是被动的。

您可以在此处详细了解Array反应性:https://vuejs.org/v2/guide/list.html#ad

2)取决于您的代码,但不应该。但我认为您目前的实施comments -> article是不对的(见第3页)

3)我希望你的后端有正确的关系article -> comments(idk,可能是你的项目是特定的,这是必要的)

所以你需要重构你的前端来做这个article->comments

开始时,最好将商店拆分为模块ArticleComment

这只是一些重构。如果你需要一些架构建议,那么你需要提供更多信息,而不仅仅是输出\一些基本动作代码

答案 1 :(得分:1)

Vuex突变

  

我的第一个问题是如何在不使用Vue.set的情况下改变一个对象(这里)?

Mutations follow vue's reactivity rules

这意味着当您对状态中声明的属性进行更改时,它将像vue实例上的属性一样被修改。因此,您在代码段评论中提到的时候真的不需要vue.set

受突变影响的变化

  

其次,在观察每篇文章中的注释时,使用像comments()这样的计算属性{return this。$ store.comments [this.articleId];当我们更新特定文章评论的评论状态时,请做其他文章'评论也得到更新?如果是这样,那么实施不好吗?

检查此fiddle,同时观看控制台。如果我将评论推送到id = 0,那么手表会告诉您其他套装从未对其进行任何更改。