我正在尝试扩展这个很棒的仓库https://github.com/vueschool/learn-vuex,我能够(通过数据库)将产品成功添加到购物车中。接下来,我要向购物车中的所有物品添加“删除物品”按钮。我已经尝试通过添加新的mutator和action来尝试“ addtocart”逻辑,但似乎无法使其正常工作。
ShoppingCart.vue
<template>
<div>
<h1>Shopping Cart</h1>
<ul>
<li v-for="product in products">
{{product.title}} - {{product.price | currency}} -
{{product.quantity}}
</li>
</ul>
<p>Total: {{total | currency}}</p>
<button @click="checkout">Checkout</button>
<p v-if="checkoutStatus">{{checkoutStatus}}</p>
</div>
</template>
<script>
import {mapState, mapGetters, mapActions} from 'vuex'
export default {
computed: {
...mapGetters('cart', {
products: 'cartProducts',
total: 'cartTotal'
}),
...mapState('cart', {
checkoutStatus: state => state.checkoutStatus
})
},
methods: {
...mapActions('cart', ['checkout'])
}
}
</script>
Cart.js
export default {
namespaced: true,
state: {
// {id, quantity}
items: [],
checkoutStatus: null
},
getters: {
cartProducts (state, getters, rootState, rootGetters) {
return state.items.map(cartItem => {
const product = rootState.products.items.find(product
=> product.id === cartItem.id)
return {
title: product.title,
price: product.price,
quantity: cartItem.quantity
}
})
},
cartTotal (state, getters) {
return getters.cartProducts.reduce((total, product) =>
total + product.price * product.quantity, 0)
},
},
mutations: {
pushProductToCart (state, productId) {
state.items.push({
id: productId,
quantity: 1
})
},
incrementItemQuantity (state, cartItem) {
cartItem.quantity++
},
setCheckoutStatus (state, status) {
state.checkoutStatus = status
},
emptyCart (state) {
state.items = []
}
},
actions: {
addProductToCart({state, getters, commit, rootState,
rootGetters}, product) {
if (rootGetters['products/productIsInStock'](product)) {
const cartItem = state.items.find(item => item.id ===
product.id)
if (!cartItem) {
commit('pushProductToCart', product.id)
} else {
commit('incrementItemQuantity', cartItem)
}
commit('products/decrementProductInventory',
product, {root: true})
}
},
}