zoukankan      html  css  js  c++  java
  • 关于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);
    },
  • 相关阅读:
    Redis 分布式锁
    Angular VS Blzaor
    Chorme 跨域的快捷解决
    旋转3角形
    .Netcore AD 操作
    .Netcore 2.2 和3.1 的模板
    Command3
    CSS Selector
    弹性盒子
    Label_strange_labels
  • 原文地址:https://www.cnblogs.com/xiaonian8/p/14132690.html
Copyright © 2011-2022 走看看