vue2中this.$set方法的使用实例

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 响应式系统未能及时跟踪变化而导致视图更新不及时的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值