vue开发中常用方法笔记
this.$set()
在 Vue.js 2.x 中,
this.$set
是用于解决响应式系统限制的核心 API,特别是在处理动态数据结构和第三方 API 返回数据时尤为重要。1.对象属性动态添加
this.userProfile.age = 27 // 错误方式(不会触发更新)
this.$set(this.userProfile, 'age', 27) // 正确方式
2.数组元素修改
this.items[index] = newValue // 错误方式(不会触发更新)
this.$set(this.items, index, newValue) // 正确方式
底层原理:
Vue 2 使用
Object.defineProperty
实现响应式,初始化时对已有属性创建 getter/setter,新增属性无法自动获得响应性,直接通过索引修改数组元素无法被检测
this.$set
内部会:检测目标类型(对象/数组),对对象使用Vue.set
添加响应式属性,对数组使用 splice 方法触发更新,通知依赖进行重新渲染
替代方案:
this.userProfile = Object.assign({}, this.userProfile, { age: 27 })