Nuxt / Vue - 不要在突变处理程序之外改变 vuex 存储状态

Nuxt / Vue - Do not mutate vuex store state outside mutation handlers

我有一个简单的购物车商店,用于添加/删除商品。

当您将产品添加到购物车时,我会显示一条闪现消息,可以更新数量。由于我不知道我的闪信组件中涉及到哪个产品,所以我使用商店。

我有一个简单的 bootstrap 微调器:

    <b-form-spinbutton
      :value="value"
      min="1"
      max="26"
      @change="setItems"
    />

当我更改它时,我想调用我商店的 setItems 函数来更新最后添加的商品。

所以我用了:

  data () {
    return {
      value: 1
    }
  },
  methods: {
    setItems (value) {
      const items = [...this.$store.getters['cart/items']]
      // update quantity of the last item - we suppose it's the current item
      items.slice(-1)[0].quantity = value
      this.$store.commit('cart/setItems', items)
    }
  }

我在这里读到这个错误:,所以我将 v-model 更改为 value 方法。

我的商店 cart.js 是:

export const state = () => ({
  items: []
})

export const mutations = {
  setItems (state, items) {
    state.items = items
  },
  // ....

我不知道如何处理这个问题?

存储状态在突变处理程序之外发生突变的行是:

items.slice(-1)[0].quantity = value

通过使用展开运算符,您可以创建商店商品的浅表副本。每个项目 属性 仍然引用 vuex 状态。您可以创建深拷贝,使用:

const items = JSON.parse(JSON.stringify(this.$store.getters['cart/items']))

或者,如果您的项目中有 lodash:

const items = _.cloneDeep(this.$store.getters['cart/items'])