vuex报错

在使用vuex时报错
Cannot read property apply of undefined at VueComponent.mappedAction

我的代码:

  <div>
    商品列表
    <ul v-for="product in products">
      <li>{{product.title}} - {{product.price}}</li>
      <button @click="addCartsAction(product.id)">添加购物车</button>
    </ul>
  </div>
</template>
<script>
  import {mapState, mapActions} from 'vuex'
  export default {
    name: "product-list",
    computed: {
      ...mapState(['products'])
    },
    methods: {
      ...mapActions(['addCartsAction'])
    },
  }
</script>
<style scoped>
</style>


//store/index文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
var state = {
  products: [
    {"id": 1, "title": "iPad 4 Mini", "price": 500.01},
    {"id": 2, "title": "H&M T-Shirt White", "price": 10.99},
    {"id": 3, "title": "Charli XCX - Sucker CD", "price": 19.99}
  ],
  carts: [{id: 1, count: 1}]
};
var actions = {
  addCartsAction({state, commit}, id) {
    commit('addCarts', id)
  }
};
var mutations = {
  addCarts(state, id) {
    state.carts.push({
      id: id,
      count: 1
    })
  }
};
export default {
  state,
  mutations,
  actions,
}

我现在主要是只要使用addCartsAction函数就会报错

阅读 2.7k
1 个回答

Vue 中store需要是Vuex.Store对象, 在export 的时候需要new一个这个对象。

最后一部分代码改成下面这样:

export default new Vuex.Store({
  state,
  mutations,
  actions
});
宣传栏