Javascript 不要在变异处理程序外变异Vuex。如何反应式更新阵列?
我的目标是反应性地改变数组的对象,我希望每当我在组件上调用此操作时它都会更新 Index.vueJavascript 不要在变异处理程序外变异Vuex。如何反应式更新阵列?,javascript,vue.js,vuex,Javascript,Vue.js,Vuex,我的目标是反应性地改变数组的对象,我希望每当我在组件上调用此操作时它都会更新 Index.vue <select @change="onChange($event, product)"> <option></option> </select> store/index.js export const state = () => ({ cart: [ {"_id": 1, "quantity": 2},
<select @change="onChange($event, product)">
<option></option>
</select>
store/index.js
export const state = () => ({
cart: [
{"_id": 1, "quantity": 2},
{"_id": 12, "quantity": 4},
{"_id": 9, "quantity": 99},
{"_id": 3, "quantity": 14}
]
});
export const mutations = {
changeQuantity(state, { product, qty }) {
// Find a targeted product in the cart
let cartProduct = state.cart.find(item => item._id === product._id);
// Find the Index
let indexOfProduct = state.cart.indexOf(cartProduct);
// Change the quantity
cartProduct.quantity = qty;
// Create a new copy and assign it to the same variable
cartProduct = Object.assign({}, cartProduct);
// Removed and update with a new object, Reason why I use splice is because
// of the reactivity
state.cart.splice(indexOfProduct, 1, cartProduct);
},
}
第一次可以,但第二次显示错误
[vuex]不要在变异处理程序之外变异vuex存储状态
改变数组并立即更新它的行业标准是什么?为什么在
Object.assign()之前设置数量
?我认为错误不太可能来自您问题中的代码,因为在变异之外没有发生任何事情。我无法用提供的代码重现这一点~为什么要在Object.assign()之前设置数量
?我认为错误不太可能来自您问题中的代码,因为在变异之外没有发生任何事情。我无法用提供的代码重现这一点~