华域联盟 JAVA 关于Vue不能监听(watch)数组变化的解决方法

关于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无法监听数组变化的情况

但是数组在下面两种情况下无法监听

  • 利用索引直接设置数组项时,例如arr[indexofitem]=newValue
  • 修改数组的长度时,例如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);
},

到此这篇关于关于Vue不能监听(watch)数组变化的文章就介绍到这了,更多相关Vue不能监听数组变化内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » 关于Vue不能监听(watch)数组变化的解决方法

转载请保留出处和原文链接:https://www.cnhackhy.com/82630.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部