VueJS-未知的本地操作类型:addProductToCart,全局类型:cart / addProductToCart

时间:2018-10-04 15:10:50

标签: vue.js vuex

我对VueJS来说还很陌生,所以请放轻松。我正在尝试使用VueJS实现购物车。我有一个名为“添加到购物车”的按钮,它带有一个名为addProductToCart(product)的点击处理程序,应将产品添加到购物车中,当我单击该按钮时,我将收到一个错误unknown local action type: addProductToCart, global type: cart/addProductToCart。我被困住了,我不知道自己做错了什么。

Component.vue

<button @click="addProductToCart(product)">Add to Cart</button>

<script>
    import { mapActions } from 'vuex'

    export default {
      computed: {
        //...
      },
      methods: mapActions('cart', [
        'addProductToCart'
      ])
    }
</script>

store / modules / cart.js

import * as types from '../types';

const state = {
  items: []
};

const getters = {
  cartProducts: (state, getters, rootState) => {
    return state.items.map(({ name, quantity }) => {
      const product = rootState.products.all.find(product => product.name === name)
      return {
        name: product.name,
        price: product.price,
        quantity
      }
    })
  },
  cartTotalPrice: (state, getters) => {
    return getters.cartProducts.reduce((total, product) => {
      return total + product.price * product.quantity
    }, 0)
  }
};

const mutations = {
  [types.PUSH_PRODUCT_TO_CART] (state, { product_name }) {
    state.items.push({
      product_name,
      quantity: 1
    })
  }
};

const actions = {
  [types.ADD_PRODUCT_TO_CART] ({ state, commit }, product) {
    commit(types.PUSH_PRODUCT_TO_CART, { name: product.name })
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

types.js

export const ADD_PRODUCT_TO_CART = 'cart/ADD_PRODUCT_TO_CART'
export const PUSH_PRODUCT_TO_CART = 'cart/PUSH_PRODUCT_TO_CART'

我正在使用命名空间模块,因为我具有产品状态和购物车状态,并且希望每个状态分别具有不同的动作,突变等。

1 个答案:

答案 0 :(得分:2)

问题是您的操作签名为[types.ADD_PRODUCT_TO_CART]不正确。

应该是:

const actions = {
  addProductToCart ({ state, commit }, product) {
    commit(types.PUSH_PRODUCT_TO_CART, { name: product.name })
  }
};