vue項目中,更改數組元素的值,視圖沒有實時更新?

問題背景:

export default {
  data(){
    showItems: [false, false, false, false]
  },
  methods: {
    showItem(index) {
      this.showItems[index] = true;
    },
    cancelItem(index) {
      this.showItems[index] = false;
    },
  },
}

如上程式碼,定義了showItems數組之後,通過點擊按鈕觸發showItem和cancelItem函數來更改數組元素的值,發現頁面上使用showItems數組元素的值並沒有刷新,審查元素(如下圖)找到該值,繼續觸發事件並查看發現元素值沒有隨著事件的觸發而改變

原因:

由於 JavaScript 的限制及Vue實現響應式數據的原理,Vue 不能檢測數組和對象的變化,具體原因參考Vue官網,我並沒有對此深入理解。

解決方法:

我列出了三個解決方法:

  1. this.$forceUpdate()

用法:
迫使 Vue 實例重新渲染。注意它僅僅影響實例本身和插入插槽內容的子組件,而不是所有子組件。參考Vue官網vm-forceUpdate

export default {
  data(){
    showItems: [false, false, false, false]
  },
  methods: {
    showItem(index) {
      this.showItems[index] = true;
      this.$forceUpdate()
    },
    cancelItem(index) {
      this.showItems[index] = false;
      this.$forceUpdate()
    },
  },
}
  1. this.$set(object, propertyName, value)

用法:
向響應式對象中添加一個 property,並確保這個新 property 同樣是響應式的,且觸發視圖更新。它必須用於向響應式對象上添加新 property,因為 Vue 無法探測普通的新增 property,參考Vue官網Vue-set

export default {
  data(){
    showItems: [false, false, false, false]
  },
  methods: {
    showItem(index) {
      this.$set(this.showItems, index, true)
    },
    cancelItem(index) {
      this.$set(this.showItems, index, false)
    },
  },
}
  1. .push()

用法:

所以使用Vue包裹過的方法可以觸發數據雙向綁定

export default {
  data(){
    showItems: [false, false, false, false]
  },
  methods: {
    showItem(index) {
     this.showItems[index] = true;
     this.showItems.push();
    },
    cancelItem(index) {
      this.showItems[index] = false;
      this.showItems.push();
    },
  },
}