【问题标题】:Best way to update an object's value in array (state) in Vuex在 Vuex 中更新数组(状态)中对象值的最佳方法
【发布时间】:2021-10-04 13:32:46
【问题描述】:

目前,我使用 Vuex 在 Vue 中制作了一个简单的购物车。我遇到的问题是我正在更新购物车对象中产品的数量,但这不会在前端视图上更新(它不是反应式的)。

我目前所做的是更新 cart 数组中的一个对象值,为了让它工作,我需要将现有的购物车设置为一个空数组,然后我重新应用具有新值的旧购物车状态。

更新数组中对象值的最佳方法是什么?

以下是我的模块(vuex)中的以下相关数据:

    namespaced: true,
    state: {
        cart: [],
        products: [
            {
                id: 2,
                name: 'Product sweater 2',
            },
            {
                id: 1,
                name: 'Product sweater',
            }
        ]
    },
    mutations: {

        update(state, product) {

            const index = state.cart.findIndex(x => x.id === product.id)

            if (index !== -1) {
                state.cart[index].quantity++
                state.cart = [
                    ...state.cart
                ]
            } else {
                product.quantity = 1
                state.cart.push(product)
            }
        },
   }

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    您可以使用 Vue.set 和 Vue.delete 来更改 vue.js 中的数组和对象。 Vue.set 是一个工具,它允许我们向已经反应的对象添加和更改属性。

    Vue.set - API

    Reactivity in Depth

    【讨论】:

      【解决方案2】:

      如果您发送对象的索引会更好,这样可以轻松更新特定值而无需搜索数组中的项目,否则您可以按照以下方法进行

      mutations: {
          update(state, product) {
              // Find index of the item to be updated
              const itemIndex = state.cart.findIndex(x => x.id === product.id)
              state.cart[itemIndex] = product;
          }
      }
      

      【讨论】:

      • 感谢您的回答。我已经按照你的方式完成了,使用索引,它可以工作,但不幸的是它不是被动的
      • 你在你的 vue 组件中使用mapState 吗?
      【解决方案3】:

      你可以试试这样的。代码不言自明

      mutations: {
          update(state, product) {
              // Find product index in cart
              const index = state.cart.findIndex(x => x.id === product.id)
              if (index !== -1) {
                  // If product is found, update properties
                  let productFound = state.resources[index]
                  productFound.quantity++
                  // Update the product in state
                  state.cart = [...state.cart.slice(0, index), { ...productFound, ...product }, ...state.cart.slice(index + 1)]
              } else {
                  // Add product to state
                  product.quantity = 1
                  state.cart.push({ ...product })
              }
          }
      }
      

      【讨论】:

      • 感谢您的回答。在尝试了您的解决方案后,不幸的是它不起作用。它似乎没有更新数量并且没有反应
      猜你喜欢
      • 2017-04-27
      • 2020-08-12
      • 1970-01-01
      • 2021-09-09
      • 2021-06-07
      • 2015-03-23
      相关资源
      最近更新 更多