[英]Vue component toggle button with vuex store
I try make cart vue component and buttons "add to cart" component using vuex.我尝试使用 vuex 制作购物车 vue 组件和按钮“添加到购物车”组件。 When item is not in cart I show button.
当商品不在购物车中时,我会显示按钮。 When push button - item will add to cart and will be replaced by quantity in cart (for testing).
按下按钮时 - 项目将添加到购物车并被购物车中的数量替换(用于测试)。
Now I need push button 2 times to display quantity.现在我需要按两次按钮来显示数量。 Data added in cart on first click.
首次点击时将数据添加到购物车中。 But only in second click it replaced.
但只有在第二次点击它才被替换。 Where I make mistake?
我在哪里犯错? What can I do?
我能做些什么?
My vue component我的 Vue 组件
<template>
<div>
<div v-if="productInCart">
{{productInCart.quantity}}
</div>
<div v-else>
<button type="button" class="btn btn-primary" @click="add()">
To Cart
</button>
</div>
</div>
</template>
<script>
import {mapActions, mapGetters} from 'vuex';
export default {
name: "Test",
props: [
'data'
],
created: function() {
this.product = JSON.parse(this.data);
},
data() {
return {
product: null,
}
},
computed: {
...mapGetters({
cartItem: 'cartItem'
}),
productInCart: function () {
return this.$store.getters.cartItem(this.product.id)
},
},
methods: {
...mapActions({
addToCart: 'addToCart',
}),
add() {
this.addToCart({
'id': this.product.id,
'name': this.product.name,
'price': this.product.price,
'quantity': 1,
'attributes': null
})
},
},
}
</script>
My vuex store我的 vuex 商店
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
items: {
303: {id: 303, name: 'p3', quantity: 10, price: 7, attributes: null},
304: {id: 304, name: 'p4', quantity: 15, price: 8, attributes: null},
},
},
getters: {
cartItems: state => {
return state.items;
},
cartItem: state => row => {
return state.items[row];
},
},
mutations: {
addToCart(state, item) {
state.items[item.id] = item;
},
removeFromCart(state, item) {
if (item.id in state.items){
Vue.delete(state.items, item.id);
}
},
},
actions: {
addToCart(store, item) {
store.commit('removeFromCart', item);
if (item.quantity > 0) {
store.commit('addToCart', item);
}
},
removeFromCart(store, item) {
store.commit('removeFromCart', item);
},
},
});
Poblem and solution in Object Change Detection Caveats . 对象变化检测注意事项中的问题和解决方案。
addToCart(state, item) {
Vue.set(state.items, item.id, item);
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.