Не изменяйте Vuex вне обработчика мутаций. Как реактивно обновить массив? - PullRequest
1 голос
/ 18 октября 2019

Моя цель - реактивное изменение объекта массива, я хочу, чтобы он обновлялся всякий раз, когда я вызываю это действие для моего компонента

Index.vue

<select @change="onChange($event, product)">
  <option></option>
</select>
onChange(event, product) {
   let qty = event.target.value
    // Assuming product is an object { _id: 23, quantity: 23 }
   this.$store.commit("changeQuantity", {product, qty})
}   

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 вне обработчиков мутаций.

Что является отраслевым стандартом для изменения массива и его немедленного обновления?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...