Vue-给对象新增响应式属性(使用Vue.$set()或者Object.assign())
Vue.$set给对象新增属性在开发过程中,我们时常会遇到这样一种情况:当vue的data里边声明或者已经赋值过的对象或者数组(数组里边的值是对象)时,向对象中添加新的属性,如果更新此属性的值,不会更新视图。根据官方文档定义:如果在实例创建之后添加新的属性到实例上,它不会触发视图更新。受 ES5 的限制,Vue.js 不能检测到对象属性的添加或删除。因为 Vue.js 在初始化实例时将属性...
Vue.$set给对象新增属性
- Vueset_32">Vue.$set()
- Object.assign()
- $set()方法不生效时,改用Object.assign()试试
你越是认真生活,你的生活就会越美好
建议读读Vue官方文档深入响应式原理
的介绍,对这一块你的理解会加深很多
vuejs.org/v2/guide/reactivity.html">深入响应式原理
vue代码中,只要在data对象里定义的对象,赋值后,任意一个属性值发生变化
,视图都会实时变化
比如下面在data定义了obj对象,mounted里赋值后,(也可以在其他地方赋值)只要obj.a
或者obj.b
的值改变了,视图会跟着变化
data() {
return {
obj: {}
}
},
mounted: {
this.obj = {a:1, b: 2} // 改变this.obj.a this.obj.c的值视图会更新
this.obj.c = 3 // 改变this.obj.c的值 视图不会更新
Object.assign(this.obj, {d: 4}) // 改变this.obj.c的值 视图不会更新
this.$set(this.obj, 'e', 5) // 改百年this.obj.e时 视图会更新
console.log('obj' + this.obj)
}
但是我们在obj对象上新增的属性
变化时,值会变化,但是视图不会实时变化
比如obj.c
或者obj.d
变化时,值虽然会变,但是视图不会跟着变
Vueset_32">Vue.$set()
vuejs.org/v2/api/#Vue-set">Vue官方文档
使用Vue.$set()
方法,既可以新增属性
,又可以触发视图更新
,比如obj.e
改变时,视图会相应改变
打印出的obj,可以看出,新增的属性
只有通过this.set()的obj.e属性
有get
和set
方法的,而新增的obj.c
和obj.d
没有
根据官方文档定义:如果在实例创建之后
添加新的属性
到实例上,它不会触发视图更新
。
当我们把一个JavaScript 对象传入 Vue 实例作为 data 选项,Vue 将遍历此对象所有的属性,并使用 Object.defineProperty
把这些属性全部转为 getter/setter
。
Vueset_42">Vue.$set()源码
Vue2.6.12版本的源码
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
export function set (target: Array<any> | Object, key: any, val: any): any {
if (process.env.NODE_ENV !== 'production' &&
(isUndef(target) || isPrimitive(target))
) {
warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
target.splice(key, 1, val)
return val
}
if (key in target && !(key in Object.prototype)) {
target[key] = val
return val
}
const ob = (target: any).__ob__
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
)
return val
}
if (!ob) {
target[key] = val
return val
}
defineReactive(ob.value, key, val)
ob.dep.notify()
return val
}
/**
* Define a reactive property on an Object.
*/
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
}
Object.assign()
给data定义的对象新增属性
,同时又要视图实时更新
,除了用Vue.$set()
方法,也可以通过Object.assign()
实现
data() {
return {
obj: {}
}
},
mounted: {
this.obj = { a: 1, b: 2 }
this.obj.c = 3
Object.assign(this.obj, { d: 4 })
// this.$set(this.obj, 'e', 5)
// 下面这一行代码才触发了视图更新
this.obj = Object.assign({}, this.obj, {e: 5})
console.log("obj", this.obj)
}
以上的代码等同于
data() {
return {
obj: {}
}
},
mounted: {
this.obj = { a: 1, b: 2, c: 3, d: 4, e: 5 }
}
$set()方法不生效时,改用Object.assign()试试
今天一美女同事
使用this.$set()
去改变一个传入组件的对象(没有直接定义在data对象中,通过mixins选项做相关操作,能够通过this.去获取)
,没有触发视图更新
而改用Object.assign()
去给对象重新赋值时,会触发视图更新
通过重新给对象赋值
,来使视图更新;
使用Object.assign()新增,或者改变原有对象,
// 起作用的是给对象重新赋值
this.obj = Object.assign({}, this.obj, {e: 5})
谢谢你阅读到了最后~
期待你关注、收藏、评论、点赞~
让我们一起 变得更强
推荐阅读
vue%E6%BA%90%E7%A0%81&spm=1018.2118.3001.4450">Vue2.0 源码学习完整目录
更多推荐