javascript - 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 是
[]
因为我没有添加任何东西
解决方案
正如@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 。
推荐阅读
- maven - 桌面类在 NetBeans 中不起作用 - 带有 maven 的 java
- powershell - 比较超过 2 列的 2 个 CSV 文件数据
- docker - Nginx 与 docker,未找到与斜线不同的位置
- monitoring - 将服务应用到主机 - NAGIOS
- perf - 如何使用 perf_event_open() 测量 dtlb 命中和 dtlb 未命中?
- r - R数据框按类别ID过滤多个逻辑条件
- linux - 将 Linux“时间”命令的输出提取到文件中
- node.js - Sequelize:关联表查询中的“包括意外”
- python - 对具有复杂关系的数据集进行重复数据删除
- r - gtsummary:在 Markdown PDF 输出中适合宽表