我在搞乱 Vuex,我几乎让它工作了,只有这个问题困扰着我。你看,我有一个产品列表,每个产品都有自己的“addToCart()”点击事件。
将产品添加到购物车后,它应该更新 Home.vue 组件中的购物车。奇怪的是,这只会在单击第一个产品的 addToCart 按钮或您第一次为第二个产品使用该按钮时更新。只有当您单击第一个产品的按钮时,它才会更新两种产品的数量。
这是我的代码,这里是组件 Home.vue:
<template>
<div class="home">
<div v-for="product in cart" :key="product.id">
{{product.name}} {{product.quantity}}
</div>
<div v-for="product in products" :key="product.id">
{{product.name}}
<button @click="addToCart(product)">Add to cart</button>
</div>
</div>
</template>
<script>
export default {
/* eslint-disable */
name: 'Home',
data () {
return {
products: [
{
id: 1,
name: 'Appeltaart',
price: '20.00'
},
{
id: 2,
name: 'Chocoladetaart',
price: '15.40'
}
],
}
},
computed: {
cart() {
return this.$store.getters.cart
}
},
beforeMount() {
},
methods: {
addToCart(product) {
this.$store.commit('addToCart', product)
},
}
}
</script>
最后,这是我的名为 Index.js 的 Vuex 文件:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
/* eslint-disable */
state: {
cart: [],
newCartItem: {
id: 0,
name: '',
price: 0,
quantity: 0,
},
},
mutations: {
addToCart (state, product) {
console.log(state.cart)
let findProduct = state.cart.find(o => o.id === product.id)
if ( findProduct ) {
findProduct.quantity += 1;
} else {
state.newCartItem.id = product.id
state.newCartItem.name = product.name;
state.newCartItem.price = product.price;
state.newCartItem.quantity = 1;
state.cart.push(state.newCartItem)
state.newCartItem = {}
}
}
},
actions: {
},
modules: {
},
getters: {
cart: state => state.cart
}
})
点击第一个产品的addToCart时也会出现这个错误:
[Vue warn]: Duplicate keys detected: '1'. This may cause an update error.
[Vue warn]: Duplicate keys detected: '2'. This may cause an update error.
编辑不仅是第一个产品,它始终是您点击的第二个产品的 addToCart
更新修复了重复键问题