关于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);
},

2、修改数组的长度 长度大于原数组就将后续元素设置为undefined 长度小于原数组就将多余元素截掉

data () {
  return {
    watchArr: [{
      name: krry,
    }],
  };
},
watchArr (newVal) {
  console.log(监听: + newVal);
},
created () {
  setTimeout(() => {
    this.watchArr.length = 5;
  }, 1000);
},
经验分享 程序员 微信小程序 职场和发展