javascript - 当我在分派(dispatch)后更新 vue 组件中的状态时,防止状态更新

标签 javascript arrays vue.js vuex

我是这个 Vue 和 Vuex 世界的新手,我正在创建一个拥有多种产品的客户列表。为了实现这一点,我在 Vue 组件中创建了一个客户数组,其中我有产品数组,我在其中推送产品项以添加多个产品。在保存客户时,我只是将其发送到 Vuex 商店并将其推送到我所在州的客户数组。我的问题是当我在第二个客户中添加产品项目时,vuejs 在所有客户中添加产品项目。

View 组件

 data() {
    return {
      customer: {
        cus_name: ""
        cus_product: [
          {
            product_name: "",
          }
        ]
      }
    };
  },
  methods: {
    addProduct() {
      this.customer.cus_product.push({
        product_name: ""
      });
    },

    removeProduct(index) {
      this.customer.cus_product.splice(index, 1);
    },

    addCustomer() {
      this.$store.dispatch("addCustomer", this.customer);
    }
  }
};  

vuex 商店

const state = {
    customers: []
};


const mutations = {
    addCustomer(state, customerData) {
        state.customers.push(customerData);
    }
};

const actions = {
    addCustomer(vuexContext, customerData) {
        vuexContext.commit('addCustomer', customerData);
    }
};

最佳答案

当您在 addProduct() 中添加产品时,您的代码不会说明应将产品添加给谁。我的意思是您设置了 cus_name: "" 并且在您添加产品时它从未更新过。

我不知道您的整个应用程序是什么样子,但有一件事是肯定的:我们需要告诉定义必须向其添加产品的客户:

addProduct() {
  // I add the product to the customer begueradj, for instance
  this.customer.cus_name = "begueradj"
  this.customer.cus_product.push({
    product_name: ""
  });
},

那是在你的 Vue 组件中。

现在在你的商店的突变中,你必须首先寻找名字为“begueradj”的客户,那么我们将在这里面临 2 种情况:

  1. 如果客户已经存在,则只更新他的产品列表
  2. 如果客户是新客户,则将他添加到客户列表中

在简单的 Kabyle 语言中,这将引导我们得到这个简单的代码:

const mutations = {
  addCustomer(state, customerData) {
     // We check first if there is a customer whose name is the one we want to add products to:
     const customer = state.customer.find(customer => customer.cus_name === customerData.cus_name)
     if (customer) {
       // If we found him, then update his products list:  
       customer.cus_product.concat(customerData.cust_product)
     } else {
       // Customer does not exist, then add him to the customers list
       state.customer.push(customerData)
     }
  }
};

关于javascript - 当我在分派(dispatch)后更新 vue 组件中的状态时,防止状态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55663202/

相关文章:

javascript - 如何在 Javascript 中显示警报

javascript - 关于回调函数的 jQuery 术语

vue.js - 使用 VITE + Vue3 - [Vue 警告] : Component is missing template or render function

javascript - 更改 angularJS 中指令的作用域变量

javascript - IE 11 忽略动态生成的 html 页面的 appendChild()

c - Malloc() 为指向 int 数组的指针分配空间的正确方法

arrays - 如何使用 Perl 更有效地处理大型文本文件

PHP将所有参数作为数组获取?

webpack - 如何修复这些 SockJS ssl 错误?

javascript - Vue.js 和观察者模式