vue2缺陷--為對(duì)象直接新增屬性或?yàn)閿?shù)組通過下標(biāo)操作數(shù)組項(xiàng),頁面無法觸發(fā)更新解決方法

Vue 2 使用 Object.defineProperty 實(shí)現(xiàn)響應(yīng)式,這導(dǎo)致它無法檢測到對(duì)象屬性的直接添加或刪除,以及通過索引直接設(shè)置數(shù)組項(xiàng)的變化。

對(duì)象新增屬性問題

<template>
  <div>
    <p>用戶信息:{{ user }}</p>
    <button @click="addProperty">添加新屬性</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: {
        name: '張三',
        age: 25
      }
    }
  },
  methods: {
    addProperty() {
      // 直接添加新屬性不會(huì)觸發(fā)視圖更新
      this.user.gender = '男';
      console.log(this.user); // 控制臺(tái)能看到gender屬性,但視圖不會(huì)更新
      
      // 正確做法:使用Vue.set或this.$set
      // this.$set(this.user, 'gender', '男');
    }
  }
}
</script>

數(shù)組通過下標(biāo)操作問題

<template>
  <div>
    <p>列表:{{ items }}</p>
    <button @click="updateItem">更新第一項(xiàng)</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: ['蘋果', '香蕉', '橙子']
    }
  },
  methods: {
    updateItem() {
      // 通過索引直接修改數(shù)組項(xiàng)不會(huì)觸發(fā)視圖更新
      this.items[0] = '西瓜';
      console.log(this.items); // 控制臺(tái)能看到變化,但視圖不會(huì)更新
      
      // 正確做法:
      // 1. 使用Vue.set或this.$set
      // this.$set(this.items, 0, '西瓜');
      
      // 2. 使用數(shù)組的變異方法
      // this.items.splice(0, 1, '西瓜');
    }
  }
}
</script>
?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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