我的问题是,只要状态改变,吸气剂就根本不会改变。我猜是因为吸气剂无法检测到阵列中的变化?
Vuex代码
// State - Basic data for the cart
export const state = () => ({
cart: [{ _id: 1, price: 1000} , {_id: 2, price: 2000 } , { _id: 3, price: 222}],
});
//Mutations - Find the product with same id and change the price
export const mutations = () = ({
changePrice(state, { id, newPrice }) {
const cartProduct = state.cart.find(item => item._id === id);
cartProduct.price = newPrice
}
})
// Getters - Get all price and combine it so - 1000 + 2000 + 222 = 3222
export const getters = {
cartTotalPrice(state) {
return state.cart.reduce((total, product) => {
return total + product.price;
}, 0);
},
}
Price.vue
<template>
<!-- Basic input with type number and button to do an action -->
<div>
<input type="number" v-model="price" />
<button @click="onChangePrice">
<h3>{{ cartTotalPrice }}</h3>
</div>
</template>
<script>
export default {
data() {
return { price: 0 }
}
computed: {
...mapGetters(['cartTotalPrice'])
},
methods: {
onChangePrice() {
this.$store.commit('changePrice', {_id: 1, newPrice: this.price });
}
}
}
</script>
关于如何继续获得反应性吸气剂的任何建议,我应该更换阵列吗?
答案 0 :(得分:0)
我看到两个错误。
此:
this.$store.commit('changePrice', {1, this.price });
应该是这样:
this.$store.commit('changePrice', { id: 1, newPrice: this.price });
第二个问题是mutations
的定义:
export const mutations = (state, { id, newPrice }) = ({
changePrice() {
我真的不知道发生了什么,但是我想你是说这样的:
export const mutations = {
changePrice(state, { id, newPrice }) {