阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

简单介绍Vue之vue.$set()方法源码案例

29次阅读
没有评论

共计 1673 个字符,预计需要花费 5 分钟才能阅读完成。

导读 这篇文章主要介绍了 Vue 之 vue.$set() 方法源码案例详解, 本篇文章通过简要的案例, 讲解了该项技术的了解与使用, 以下就是详细内容, 需要的朋友可以参考下

在使用 vue 开发项目的过程中,经常会遇到这样的问题:当 vue 的 data 里边声明或者已经赋值过的对象或者数组(数组里边的值是对象)时,向对象中添加新的属性,如果更新此属性的值,是不会更新视图的。

这是因为新加入的属性不是响应式的,因此不会触发视图的更新,通常使用静态方法 Vue.set() 或者实例方法 this.$set() 解决,使用方式:

对象:this.$set(target,key, value)

数组:this.$set(target,index, value)

但不管是静态方法 Vue.set() 还是实例方法 this.$set(),他们底层的实现逻辑是一样的,实现逻辑如下:

/**
 * 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 | Object, key: any, val: any): any {// 首先判断如果传入的目标对象是 undefined, null, primitive( 原始值),或抛出警告
  if (process.env.NODE_ENV !== 'production' &&
    (isUndef(target) || isPrimitive(target))
  ) {warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  // 判断目标对象 target 是数组,并且 key 是合法的索引
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    // 取目标数组的 length 值和 key 中较大的值作为 target 的 length 属性
    target.length = Math.max(target.length, key)
    // 通过 splice 对 key 位置的元素进行替换
    target.splice(key, 1, val)
    return val
  }
  // 如果 key 在目标对象中已经存在,则直接赋值
  if (key in target && !(key in Object.prototype)) {target[key] = val
    return val
  }
  // 获取 target 中的 observer 对象
  const ob = (target: any).__ob__
  // 如果 target 是 vue 实例或者 $data 直接返回
  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
  }
  // 如果 ob 不存在,说明 target 不是响应式对象,直接赋值,不触发视图更新
  if (!ob) {target[key] = val
    return val
  }
  // 如果 ob 存在,把 key 设置为响应式属性
  defineReactive(ob.value, key, val)
  // 发送通知,触发视图更新
  ob.dep.notify()
  return val
}

以上是 vue 中 set 方法的源码,在这里需要特别注意的是,在对数组进行处理时,所用的 splice 方法并不是数组本身的方法,而是在 vue 中封装的具有响应式的数组方法。

到此这篇关于 Vue 之 vue.$set() 方法源码案例详解的文章就介绍到这了,感谢大家的支持。

阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配

腾讯云新客低至 82 元 / 年,老客户 99 元 / 年

代金券:在阿里云专用满减优惠券

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-07-25发表,共计1673字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中