Vue2.* Vue.set实现原理

一、对象添加属性

对于使用 Object.defineProperty实现响应式的对象,当我们去给这个对象添加一个新的属性的时候,是不能触发它的 setter 的,比如:

var vm = new Vue({
	data: {
		a: 1
	}
})

// vm.b 是非响应的
vm.b = 2

但是添加新属性的场景是我们在平时开发中会经常遇到,Vue 为了解决以上问题,提供了一个全局Api Vue.set 方法,以下是源码部分。

二、 源码部分

src/core/global-api/index.js 中,initGlobalAPI 方法会有以下赋值:

Vue.set = set

set 方法定义如下:

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

set 方法接收 3个参数,target 可能是数组或者是普通对象,key 代表的是数组的下标或者是对象的键值,val代表添加的值。首先判断如果 target 是数组且 key 是一个合法的下标,则之前通过splice 去添加进数组然后返回,这里的 splice 其实已经不仅仅是原生数组的 splice 了。接着又判断 key 已经存在于 target 中,则直接赋值返回,因为这样的变化是可以观测到了。接着再获取到target.__ob__ 并赋值给 ob,它是在 Observer 的构造函数执行的时候初始化的,表示 Observer 的一个实例,如果它不存在,则说明 target 不是一个响应式的对象,则直接赋值并返回。最后通过 defineReactive(ob.value, key, val) 把新添加的属性变成响应式对象,然后再通过 ob.dep.notify() 手动的触发依赖通知,还记得我们在给对象添加getter 的时候有这么一段逻辑:

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

  // 当 val 为 Array或Object, childOb有值
  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()  // 依赖更新
    }
  })
}

getter过程中判断了 childOb, 并调用了 childOb.dep.depend() 收集了依赖,这就是为什么执行 Vue.set的时候通过ob.dep.notify()能够通知到 watcher,从而让添加新的属性到对象也可以检测到变化,这里如果value是个数组,那么就通过 dependArray把数组每个元素也去做依赖的收集。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue中的this.$set()方法的原理是通过修改目标对象的属性值来实现响应式更新。在Vue2中,当我们通过数组的下标去修改数组值,或者向对象添加属性时,对应的视图都无法进行更新,因为添加的数据不是响应式的,无法触发视图的重新渲染。而使用this.$set()方法可以解决这个问题。 具体原理如下: 1. 首先,this.$set()方法会判断目标对象是否为undefined、null或者是基本类型值,如果是,则会提示错误。 2. 然后,如果目标对象是数组并且key是一个有效的数组索引,this.$set()方法会将目标数组的长度设置为key和当前长度的最大值,并用新的值替换指定索引位置的值。 3. 如果目标对象中已经存在属性key,并且key不是Object.prototype的属性,this.$set()方法会直接修改目标对象的属性值为新的值。 4. 如果目标对象是Vue实例或者存在__ob__属性的对象,并且不是Vue实例本身或者已有的Vue实例数量大于0,this.$set()方法会发出警告,避免在运行时向Vue实例或其根$data添加响应式属性。 5. 如果目标对象不存在__ob__属性,this.$set()方法会直接修改目标对象的属性值为新的值。 6. 最后,this.$set()方法会通过defineReactive()方法将新设置的属性变为响应式,并通知依赖更新。 通过以上步骤,this.$set()方法实现了目标对象属性的响应式更新。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [vue中this.$set()原理](https://blog.csdn.net/XuM222222/article/details/99942522)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [Vue源码学习之$set实现原理](https://blog.csdn.net/liu19721018/article/details/125554525)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值