在 Vue.js 中实施商店模式

Implementing Store Pattern in Vue.js

我正在尝试在 Vue.js 中实现商店模式,但我被卡住了。我有两个子组件,它们通过 props 将共享状态传递给它们。每个子组件对传入的道具做不同的事情。comp-a 有一个输入和两个按钮,用户可以在其中将单词添加到列表或完全清空列表,而 comp-b 负责映射并显示单词数组。我能够像这样映射单词数组:

Vue.component('comp-b', {
   props: ['astore'],
   template: '#comp-b',
   data: function(){
     return {
       words: store.state.words
     }
   },
   computed: {
     theWords: function(){
       return this.words.map(function(word){
         return word
      })
   }
  }
})

我在弄清楚如何清空单词列表时遇到了一些困难,这样通过单击 Empty words 按钮它会更新 comp-b 中显示的内容(这应该没什么,因为单词现在已经已从单词列表中清除)

这是一个演示:http://codepen.io/p-adams/pen/oLpzPA

要清除数组,您可以使用

clear: function(){ return this.state.words.splice(0); }

基于此https://vuejs.org/guide/list.html#Mutation-MethodsVueJS在使用拼接时触发视图更新