1. 程式人生 > >vue專案中,更改陣列元素的值,檢視沒有實時更新?

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陣列元素的值並沒有重新整理,審查元素(如下圖)找到該值,繼續觸發事件並檢視發現元素值沒有隨著事件的觸發而改變 ![](https://img2020.cnblogs.com/blog/1360708/202103/1360708-20210331092531540-237225926.png) ###原因: 由於 JavaScript 的限制及Vue實現響應式資料的原理,Vue 不能檢測陣列和物件的變化,具體原因參考[Vue官網](https://cn.vuejs.org/v2/guide/reactivity.html#%E5%A6%82%E4%BD%95%E8%BF%BD%E8%B8%AA%E5%8F%98%E5%8C%96),我並沒有對此深入理解。 ###解決方法: 我列出了四種(其中一種是評論者提供的)解決方法: 1. this.$forceUpdate() >用法: 迫使 Vue 例項重新渲染。注意它僅僅影響例項本身和插入插槽內容的子元件,而不是所有子元件。參考[Vue官網vm-forceUpdate](https://cn.vuejs.org/v2/api/#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() }, }, } ``` 2. this.$set(object, propertyName, value) >用法: 向響應式物件中新增一個 property,並確保這個新 property 同樣是響應式的,且觸發檢視更新。它必須用於向響應式物件上新增新 property,因為 Vue 無法探測普通的新增 property,參考[Vue官網Vue-set](https://cn.vuejs.org/v2/api/#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) }, }, } ``` 3. .push() >用法: ![](https://img2020.cnblogs.com/blog/1360708/202103/1360708-20210331102159945-1288460512.png) 所以使用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(); }, }, } ``` 4. .splice() >此方法就是經過Vue包裹後的方法之一,還是下面可愛的評論者提供的,贊 ``` export default { data(){ showItems: [false, false, false, false] }, methods: { showItem(index) { this.splice(index, 1, true); }, cancelItem(index) { this.splice(index, 1, false); }, }, } ```