欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue.set()和this.$set()使用和區(qū)別

 更新時間:2021年06月02日 11:10:19   作者:Mr_Ma  
我們發(fā)現(xiàn)Vue.set()和this.$set()這兩個api的實(shí)現(xiàn)原理基本一模一樣,那么Vue.set()和this.$set()的區(qū)別是什么,本文詳細(xì)的介紹一下,感興趣的可以了解一下

在我們使用vue進(jìn)行開發(fā)的過程中,可能會遇到一種情況:當(dāng)生成vue實(shí)例后,當(dāng)再次給數(shù)據(jù)賦值時,有時候并不會自動更新到視圖上去; 當(dāng)我們?nèi)タ磛ue文檔的時候,會發(fā)現(xiàn)有這么一句話:如果在實(shí)例創(chuàng)建之后添加新的屬性到實(shí)例上,它不會觸發(fā)視圖更新。 如下代碼,給 student對象新增 age 屬性

data () {
  return {
    student: {
      name: '',
      sex: ''
    }
  }
}
mounted () { // ——鉤子函數(shù),實(shí)例掛載之后
  this.student.age = 24
}

受 ES5 的限制,Vue.js 不能檢測到對象屬性的添加或刪除。因?yàn)?Vue.js 在初始化實(shí)例時將屬性轉(zhuǎn)為 getter/setter,所以屬性必須在 data 對象上才能讓 Vue.js 轉(zhuǎn)換它,才能讓它是響應(yīng)的。

正確寫法:this.$set(this.data,”key”,value')

mounted () {
  this.$set(this.student,"age", 24)
}

:: Vue 不允許動態(tài)添加根級響應(yīng)式屬性。

例如:

const app = new Vue({
  data: {
    a: 1
  }
  // render: h => h(Suduko)
}).$mount('#app1')

Vue.set(app.data, 'b', 2)

只可以使用 Vue.set(object, propertyName, value) 方法向嵌套對象添加響應(yīng)式屬性,例如

var vm=new Vue({
    el:'#test',
    data:{
        //data中已經(jīng)存在info根屬性
        info:{
            name:'小明';
        }
    }
});
//給info添加一個性別屬性
Vue.set(vm.info,'sex','男');

Vue.set()和this.$set()實(shí)現(xiàn)原理

我們先來看看Vue.set()的源碼:

import { set } from '../observer/index'

...
Vue.set = set
...

再來看看this.$set()的源碼:

import { set } from '../observer/index'

...
Vue.prototype.$set = set
...

結(jié)果我們發(fā)現(xiàn)Vue.set()和this.$set()這兩個api的實(shí)現(xiàn)原理基本一模一樣,都是使用了set函數(shù)。set函數(shù)是從 ../observer/index 文件中導(dǎo)出的,區(qū)別在于Vue.set()是將set函數(shù)綁定在Vue構(gòu)造函數(shù)上,this.$set()是將set函數(shù)綁定在Vue原型上。

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
}

我們發(fā)現(xiàn)set函數(shù)接收三個參數(shù)分別為 target、key、val,其中target的值為數(shù)組或者對象,這正好和官網(wǎng)給出的調(diào)用Vue.set()方法時傳入的參數(shù)參數(shù)對應(yīng)上。

參考:

vue中遇到的坑 --- 變化檢測問題(數(shù)組相關(guān))

到此這篇關(guān)于Vue.set()和this.$set()使用和區(qū)別的文章就介紹到這了,更多相關(guān)Vue.set()和this.$set()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論