【发布时间】:2020-02-17 23:17:37
【问题描述】:
我的问题是,每当状态发生变化时,getter 都不会发生变化。我猜是因为吸气剂无法检测到数组中的变化?
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);
},
}
价格.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>
关于如何继续获得反应式吸气剂的任何建议,我应该更换数组吗?
【问题讨论】:
-
在使用状态中的数组和对象时,您需要使用 Vue.set() 或完全替换 Mutation 中的状态对象,否则它不是反应性的。此外,您应该只通过操作调用 Mutation,而不是在您的 UI 中。在该操作中,您实际上会查找产品,然后将状态的新副本作为有效负载传递到突变中。基本上尽量避免突变中的业务逻辑。我什至会说“changePrice”应该是您的 Action,这应该称为更通用的“更新购物车”突变。
-
你能展示一些我需要一些可视化的例子吗