使用Vue.$set()或者Object.assign()修改对象新增响应式属性的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

使用Vue.$set()或者Object.assign()修改对象新增响应式属性的方法

梦之归途   2022-12-09 我要评论

首先建议先读读Vue官方文档深入响应式原理的介绍,对这一块你的理解会加深很多
深入响应式原理

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变化时,值虽然会变,但是视图不会跟着变

在这里插入图片描述

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。

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})

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们