關於Vue不能監聽(watch)數組變化


一、vue監聽數組
vue實際上可以監聽數組變化,比如

data () {
  return { watchArr: [], }; }, watchArr (newVal) { console.log('監聽:' + newVal); }, created () { setTimeout(() => { this.watchArr = [1, 2, 3]; }, 1000); },

在比如使用splice(0,2,3)從數組下標0刪除兩個元素,並在下標0插入一個元素3

data () {
  return { watchArr: [1, 2, 3], }; }, watchArr (newVal) { console.log('監聽:' + newVal); }, created () { setTimeout(() => { this.watchArr.splice(0, 2, 3); }, 1000); },

push數組也能夠監聽到。


二、vue無法監聽數組變化的情況
但是數組在下面兩種情況下無法監聽

  1. 利用索引直接設置數組項時,例如arr[indexofitem]=newValue
  2. 修改數組的長度時,例如arr.length=newLength

舉例無法監聽數組變化的情況
1、利用索引直接修改數組值

data () {
  return { watchArr: [{ name: 'krry', }], }; }, watchArr (newVal) { console.log('監聽:' + newVal); }, created () { setTimeout(() => { this.watchArr[0].name = 'xiaoyue'; }, 1000); },

資源搜索網站大全 https://www.renrenfan.com.cn 廣州VI設計公司https://www.houdianzi.com

2、修改數組的長度
長度大於原數組就將后續元素設置為undefined
長度小於原數組就將多余元素截掉

 
data () {
  return { watchArr: [{ name: 'krry', }], }; }, watchArr (newVal) { console.log('監聽:' + newVal); }, created () { setTimeout(() => { this.watchArr.length = 5; }, 1000); },


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM