如何使双向绑定中的数据失效?

答:

Vue 2 双向绑定对添加或者删除数据是不会自动响应式的。可以使用 Object.defineProperty 对属性重新定义 getter/setter 来实现,最简便的方法是先删除原先的数据再重新添加。

补充:

Vue 2 中让动态添加/删除的数据也保持响应式的几种方法:

  1. 使用 Vue.set (或 this.$set):给对象添加新属性。

    this.$set(this.obj, 'newKey', 'newValue')
    
  2. 使用 Vue.delete (或 this.$delete):删除对象属性。

    this.$delete(this.obj, 'oldKey')
    
  3. 重新赋值整个对象:用 Object.assign 或扩展运算符创建新对象赋值。

    this.obj = Object.assign({}, this.obj, { newKey: 'newValue' })
    // 或
    this.obj = { ...this.obj, newKey: 'newValue' }
    
  4. 使用 this.$forceUpdate():强制刷新视图(不推荐,99% 的情况是代码本身有问题)。

Vue 3 中由于使用 Proxy 替代了 Object.defineProperty,动态添加/删除属性天然就是响应式的,不需要这些特殊处理。

来源整理自:vue3js.cn 面试官系列