关于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);
},
    原文作者:666888
    原文地址: https://segmentfault.com/a/1190000019214550
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞