亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Vue之vue.$set()方法源碼案例詳解

 更新時間:2021年08月30日 16:03:15   作者:lmew  
這篇文章主要介紹了Vue之vue.$set()方法源碼案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下

在使用vue開發(fā)項目的過程中,經(jīng)常會遇到這樣的問題:當vue的data里邊聲明或者已經(jīng)賦值過的對象或者數(shù)組(數(shù)組里邊的值是對象)時,向?qū)ο笾刑砑有碌膶傩?,如果更新此屬性的值,是不會更新視圖的。

這是因為新加入的屬性不是響應(yīng)式的,因此不會觸發(fā)視圖的更新,通常使用靜態(tài)方法Vue.set()或者實例方法this.$set()解決 ,使用方式:

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

數(shù)組:this.$set(target,index,  value)

但不管是靜態(tài)方法Vue.set()還是實例方法this.$set(),他們底層的實現(xiàn)邏輯是一樣的,實現(xiàn)邏輯如下:

/**
 * 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 {
  // 首先判斷如果傳入的目標對象是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是數(shù)組,并且key是合法的索引
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    // 取目標數(shù)組的length值和key中較大的值作為target的length屬性
    target.length = Math.max(target.length, key)
    // 通過splice對key位置的元素進行替換
    target.splice(key, 1, val)
    return val
  }
  // 如果key在目標對象中已經(jīng)存在,則直接賦值
  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不是響應(yīng)式對象,直接賦值,不觸發(fā)視圖更新
  if (!ob) {
    target[key] = val
    return val
  }
  // 如果ob存在,把key設(shè)置為響應(yīng)式屬性
  defineReactive(ob.value, key, val)
  // 發(fā)送通知,觸發(fā)視圖更新
  ob.dep.notify()
  return val
}

以上是vue 中set方法的源碼,在這里需要特別注意的是,在對數(shù)組進行處理時,所用的splice方法并不是數(shù)組本身的方法,而是在vue中封裝的具有響應(yīng)式的數(shù)組方法。

到此這篇關(guān)于Vue之vue.$set()方法源碼案例詳解的文章就介紹到這了,更多相關(guān)Vue之vue.$set()方法源碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論