无法正确添加到Vuex存储

时间:2017-05-08 17:33:24

标签: javascript vue.js vuejs2 vuex

我有这个Vuex 2商店:

const datastore = new Vuex.Store({
  state: {          
    socketcluster: {
      connection: false,
      channels: []
    },
    selected_offers: []
  },
  mutations: {
    addOffer: function(offer) {
      datastore.state.selected_offers.push(offer) // first problem: cannot just use state.offers as it throws an undefined
    }
  },
  getters: {
    getOffers: function(){
      return datastore.state.selected_offers; 
    }
  }
});

在Vue 2组件中,我做了:

  methods: {
    clicked: function(){
      console.log("Toggle Offer");
      if ( datastore.getters.getOffers.filter(function(o){ o.id == this.offer.id } ).length == 0 ) {
        // add it
        datastore.commit('addOffer', this.offer)
      } else {
        // TODO remove it
      }
    }
}

当我触发方法时,商店会发生如下变化:

enter image description here

我做错了什么?

2 个答案:

答案 0 :(得分:2)

这是一种使用vuex模式的简单方法,在大型应用程序中,您应该使用操作而不是直接从组件中改变状态"就像我做的那样#34;如果是这样,我建议你阅读更多关于vuex。



const store = new Vuex.Store({
  state: {          
    socketcluster: {
      connection: false,
      channels: []
    },
    selected_offers: [ "offer1", "offer2"]
  },
  mutations: {
    addOffer: function( state, offer ) {
      state.selected_offers.push(offer);
    }
  },
  getters: {
    getOffers: function( state ){
      return state.selected_offers; 
    }
  }
});

new Vue({ 
    store,
    data: function() {
      return {
          offer: "offer3"
      }
    },
    methods: {
      clicked: function() {
        if ( this.offers.length === 2 ) {
            this.$store.commit('addOffer', this.offer)
        } else {
          // TODO remove it
        }
      }
    },
    computed: {
        offers: function() {
            return this.$store.getters.getOffers;
        }
    }
}).$mount( "#app" );

<script src="https://vuejs.org/js/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.3.1/vuex.js"></script>


<div id="app">
    <div v-for="offer in offers" > {{offer}}</div>
    <button @click="clicked"> clicked </button>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

传递给变异的第一个参数是state对象。因此,您将整个state对象推送到selected_offers数组。

您的变异方法应如下所示:

mutations: {
  addOffer: function(state, offer) {
    state.selected_offers.push(offer)
  }
},

这里是documentation for vuex mutations