首页 > 解决方案 > Vue.set 两个具有相同引用的不同对象属性

问题描述

我正在尝试使用 Vue.set 函数将对象添加到数组中,但它会将项目添加到具有相同数组属性的另一个对象中。

data() {
    return {
      ...
      form: {
        ...
        client_a: {
           ...
           items: []
        },
        client_b: {
           ...
           items: []
        },
      }
    };
  },

当我这样做时:(请注意,我正在向client_a .items 添加一个项目)

this.$set(this.form.client_a.items, 'key', { prop1: '', prop2: '' })

然后client_b .items var 的值与 client_a 相同

console.log(this.form.client_b.items)

输出

[
   'key': { prop1: '', prop2: '' }
]

this.form 的预期结果。client_b .items 是

[]

因为我没有添加任何东西

代码示例:https ://codesandbox.io/s/proud-fast-bjvyr

标签: javascriptvue.js

解决方案


正如@skirtle 指出的那样,base_client.functions-property 是同一个数组。一个简单的修复beforeMount()

beforeMount() {
  this.form.client_a = {
    ...this.base_client,
    functions: []
  }
  this.form.client_b = {
    ...this.base_client,
    functions: []
  }
  this.form.functions = [
    {
      key: "key-1",
      name: "Test"
    }
  ];
}

不太优雅,但应该工作。另一种方法是创建base_client一个带有返回值的方法,returns每次都生成一个新的 -array 。


推荐阅读