Vue的數(shù)據(jù)響應(yīng)式

什么是響應(yīng)式

當(dāng)一個(gè)物體對(duì)外界的變化做出反應(yīng)就叫響應(yīng)式的,如“我打你一拳,你會(huì)喊疼”。

Vue的數(shù)據(jù)響應(yīng)式

就是對(duì)數(shù)據(jù)做出改變時(shí),視圖上也會(huì)做出相應(yīng)的變化。

舉個(gè)例子

const vm = new Vue({
    el:'#app',
    data:{
        name: 'Luna'
    }
})

根據(jù)以上代碼,頁(yè)面上對(duì)應(yīng)位置會(huì)顯示Luna,如執(zhí)行vm.name='Pola',則會(huì)由Luna變成Pola。

但這是正常情況,還有些變態(tài)情況

  • 當(dāng)data為空對(duì)象時(shí),Vue會(huì)給出警告,例如。
new Vue({
  data: {},
  template: `
    <div>{{n}}</div>
  `
}).$mount("#app");
警告
  • 當(dāng)data為a,卻要在頁(yè)面中顯示b,因?yàn)閂ue只檢查第一層,可以消除警告,但不會(huì)將它轉(zhuǎn)換為響應(yīng)式的
new Vue({
  data: {
    obj: {
      a: 0 // obj.a 會(huì)被 Vue 監(jiān)聽 & 代理
    }
  },
  template: `
    <div>
      {{obj.b}}
      <button @click="setB">set b</button>
    </div>
  `,
  methods: {
    setB() {
      this.obj.b = 1; 
    }
  }
}).$mount("#app");

此時(shí)點(diǎn)擊 set b,視圖中不會(huì)顯示1,因?yàn)閂ue沒法監(jiān)聽一開始不存在的obj.b


image.png

解決方法
1、提前把key聲明好,哪怕是空值。

new Vue({
  data: {
    obj: {
      a: 0 // obj.a 會(huì)被 Vue 監(jiān)聽 & 代理
      b: undefined
    }
  },
  template: `
    <div>
      {{obj.b}}
      <button @click="setB">set b</button>
    </div>
  `,
  methods: {
    setB() {
      this.obj.b = 1; 
    }
  }
}).$mount("#app");

這時(shí)再點(diǎn)擊set b就會(huì)顯示1


image.png

2、使用Vue.set或this.$set

new Vue({
  data: {
    obj: {
      a: 0 // obj.a 會(huì)被 Vue 監(jiān)聽 & 代理
      b: undefined
    }
  },
  template: `
    <div>
      {{obj.b}}
      <button @click="setB">set b</button>
    </div>
  `,
  methods: {
    setB() {
      Vue.set(this.obj,'b',1); //也可以這么寫this.$set(this.obj,'b',1)
    }
  }
}).$mount("#app");

但是!

當(dāng)data中有數(shù)組怎么辦,如果數(shù)組長(zhǎng)度一直增加,就沒有辦法提前把key都聲明出來,每次改數(shù)組,都要用Vue.set或this.$set也很麻煩。

可以直接使用變異方法中的push

new Vue({
  data: {
    array: ["a", "b", "c"]
  },
  template: `
    <div>
      {{array}}
      <button @click="setD">set d</button>
    </div>
  `,
  methods: {
    setD() {
      this.array.push("d");
    }
  }
}).$mount("#app");

尤雨溪篡改了數(shù)組的7個(gè)API,調(diào)用后會(huì)更新UI,可參考文檔中[變異方法](https://cn.vuejs.org/v2/guide/list.html#%E5%8F%98%E5%BC%82%E6%96%B9%E6%B3%95-mutation-method
)章節(jié)。

image.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容