this.$set 是 Vue 提供的一个全局方法,其作用是向响应式对象里添加一个属性,并且确保这个新属性也是响应式的,如此一来,当该属性发生变化时,Vue 能够检测到并更新与之绑定的视图。
示例说明1
假设当前点击添加按钮的父行对象如下:
const currentParentRow = {
id: 1,
dtype: '设备',
dname: '无源互调仪',
dmodel: 'CPIM1800DR',
dnumber: '25003',
dnotes: '备注内容'
};
这个对象并没有 children 属性。当执行 if (!this.currentParentRow.children) { this.$set(this.currentParentRow, ‘children’, []); } 后,该对象就会变成:
const currentParentRow = {
id: 1,
dtype: '设备',
dname: '无源互调仪',
dmodel: 'CPIM1800DR',
dnumber: '25003',
dnotes: '备注内容',
children: []
};
并且这个 children 属性是响应式的,之后往 children 数组里添加、修改或删除元素时,Vue 都能检测到变化并更新视图。
示例说明2
假设在执行 this.$set 之前,this.currentParentRow 对象如下:
this.currentParentRow = {
id: 1,
dtype: '设备',
dname: '无源互调仪',
dmodel: 'CPIM1800DR',
dnumber: '25003',
dnotes: '备注内容',
children: [
{
id: 11,
dtype: '模块',
dname: '接收机',
dmodel: 'RM-018PIM2P-001',
dnumber: '24003',
dnotes: '备注内容'
}
]
};
然后通过 push 方法向 children 数组添加了一个新元素:
const newData = {
id: 12,
dtype: '模块',
dname: '发射机',
dmodel: 'TM-018PIM2P-002',
dnumber: '24004',
dnotes: '新模块备注'
};
this.currentParentRow.children.push(newData);
此时,虽然 children 数组已经发生了变化,但 Vue 可能没有及时检测到。接着执行 this.$set(this.currentParentRow, ‘children’, this.currentParentRow.children); 后,Vue 会重新对 this.currentParentRow.children 数组进行响应式处理,确保后续对该数组的任何操作都能正确更新视图。更新后的 this.currentParentRow 对象如下:
this.currentParentRow = {
id: 1,
dtype: '设备',
dname: '无源互调仪',
dmodel: 'CPIM1800DR',
dnumber: '25003',
dnotes: '备注内容',
children: [
{
id: 11,
dtype: '模块',
dname: '接收机',
dmodel: 'RM-018PIM2P-001',
dnumber: '24003',
dnotes: '备注内容'
},
{
id: 12,
dtype: '模块',
dname: '发射机',
dmodel: 'TM-018PIM2P-002',
dnumber: '24004',
dnotes: '新模块备注'
}
]
};
总结
this.$set(this.currentParentRow, ‘children’, this.currentParentRow.children); 这行代码的目的是确保在对 this.currentParentRow.children 数组进行操作后,Vue 能够正确检测到数组的变化并更新视图,避免因 Vue 响应式系统未能及时跟踪变化而导致视图更新不及时的问题。