关于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