2021-02-08【技术】Vue开发之watch监听数组、对象、变量操作分析

本文实例讲述了Vue开发之watch监听数组、对象、变量操作。分享给大家供大家参考,具体如下:

1.普通的watch

data() {
  return {
    frontPoints: 0
  }
},
created: function () {
      this.frontPoints="1231";
    },
watch: {
  frontPoints(newValue, oldValue) {
      console.log("监听frontPoints")
    console.log(newValue)
  }
}

打印出
//监听frontPoints
// 1231

注意:当监听数组时

data () {
    return {
        demo: [1,2]
    }
},
 mounted (){
    window.myVue = this
 },
watch: {
    demo(val){
        console.log(val)
    }
},

myVue.demo.push(3)  

结果是可以触发watch打印出:
//[1,2,3]
但是~~
watch 不能检测以下变动的数组:
所以:
当你利用索引直接设置一个项时,例如:myVue.demo[1] = 5
当你修改数组的长度时,例如:myVue.demo.length = 2
这时候你可以删除原有键,再 $set 一个新的,这样就可以触发watch

myVue.$set(myVue.demo,0,8) // [8,2,3]

2.数组的watch:深拷贝

data() {
  return {
    winChips: new Array(11).fill(0)
  }
},
watch: {
  winChips: {
    handler(newValue, oldValue) {
      for (let i = 0; i < newValue.length; i++) {
        if (oldValue[i] != newValue[i]) {
          console.log(newValue)
        }
      }
    },
    deep: true
  }
}

3.对象的watch

先来热身一下,下面代码会触发watch 吗:


会触发,因为在created方法里面重新给city赋值了一个对象,city前后的指向不同了

案例一:


不会触发, 因为created方法执行之后, city的指向没有变
如果我们期望捕获这种更新,应该这样写代码:

watch: {
    city: {
        handler: () => console.log('city changed'),
        deep: true
    }
}

将选项deep设为true能让vue捕获对象内部的变化。
此时就会触发watch中的city函数了。

案例二:

data() {
  return {
    bet: {
      pokerState: 53,
      pokerHistory: 'local'
    }
  }
},
 created() {
      this.bet.pokerHistory= 'aaa'
    }
watch: {
  bet: {
    handler(newValue, oldValue) {
      console.log(newValue)
    },
    deep: true
  }
}

同理,deep: true 此中方式监听也会触发。

拓展:

下面讨论一下watch一个数组:


那下面哪些操作会触发cities的watch回调呢?

this.cities = ['Beijing', 'Tianjin'];
this.cities.push('Xiamen');
this.cities = this.cities.slice(0, 1);
this.cities.pop();
this.cities.sort((a,b)=>a.localeCompare(b));
this.cities[0] = 'Shenzhen';
this.cities.splice(0, 1);
this.cities.length = 0;

答案是只有最后三行不会触发,大家可以自行尝试一下。

4.对象的具体属性的watch:

data() {
  return {
    bet: {
      pokerState: 53,
      pokerHistory: 'local'
    }
  }
},
computed: {
  pokerHistory() {
    return this.bet.pokerHistory
  }
},
watch: {
  pokerHistory(newValue, oldValue) {
    console.log(newValue)
  }
}

那么,如何监听数组、数组对象中的变化呢?让我们来看代码:


data() {
      return {
        arr: [1, 2],
        items: [
          {message: "one", id: "1"},
          {message: "two", id: "2"},
          {message: "three", id: "3"}
        ]
      }
    },
 mounted() {
      console.log(this.arr);
      this.arr[2] = 3;
      console.log(this.arr);//此时对象的值更改了,但是视图没有更新,也没触发watch
      console.log(this.items);
      this.items[0] = {message: 'fir11111st', id: '4'}
      console.log(this.items); //此时对象的值更改了,但是视图没有更新,也没触发watch
    },
watch: {
      arr: {
        handler(oldVal,newVal) {
          console.log("触发了handler")
         console.log(oldVal)
         console.log(newVal)
        },
        deep: true
      },
      items: {
        handler(oldVal,newVal) {
          console.log("触发了handler-items")
         console.log(oldVal)
         console.log(newVal)
        },
        deep: true
      }
    }
image.png

我们要使用this.$set 来对数组、数组对象进行修改。现在我们来修改mounted中的代码

     console.log(this.arr);
      this.$set(this.arr, 2, "3");
      console.log(this.arr);//此时对象的值更改了,视图更新,触发watch
      console.log(this.items);
      this.$set(this.items, 0, {message: 'fir11111st', id: '4'});
      console.log(this.items); //此时对象的值更改了,视图更新,触发watch

拓展

此外,关于vue中watch的详细用法,包括deep属性和immediate属性。

这样使用watch时有一个特点,就是当值第一次绑定的时候,不会执行监听函数,只有值发生改变才会执行。如果我们需要在最初绑定值的时候也执行函数,则就需要用到immediate属性。

比如当父组件向子组件动态传值时,子组件props首次获取到父组件传来的默认值时,也需要执行函数,此时就需要将immediate设为true。

new Vue({
  el: '#root',
  data: {
    cityName: "1312321321"
  },
  watch: {
    cityName: {
      handler(newName, oldName) {
       console.log("执行了监听cityName的初始化")
    },
      immediate: true
    }
  } 
})

监听的数据后面写成对象形式,包含handler方法和immediate,之前我们写的函数其实就是在写这个handler方法;

immediate表示在watch中首次绑定的时候,是否执行handler,值为true则表示在watch中声明的时候,就立即执行handler方法,值为false,则和一般使用watch一样,在数据发生变化的时候才执行handler。

使用 deep 深度监听 (对象里面的属性值发生改变)

当需要监听一个对象的改变时,普通的watch方法无法监听到对象内部属性的改变,只有data中的数据才能够监听到变化,此时就需要deep属性对对象进行深度监听。


new Vue({
  el: '#root',
  data: {
    cityName: {id: 1, name: 'shanghai'}
  },
  watch: {
    cityName: {
      handler(newName, oldName) {      
      console.log("执行了cityName监听")  
      },
    deep: true,
    immediate: true
    }
  } 
})

设置deep: true 则可以监听到cityName.name的变化,此时会给cityName的所有属性都加上这个监听器,当对象属性较多时,每个属性值的变化都会执行handler。如果只需要监听对象中的一个属性值,则可以做以下优化:使用字符串的形式监听对象属性:

watch: {
'cityName.name': {
      handler(newName, oldName) { 
     // ...    
  },
      deep: true,
      immediate: true
    }
  }

这样就只会给对象的某个特定的属性加监听器。

数组(一维、多维)的变化不需要通过深度监听,对象数组中对象的属性变化则需要deep深度监听。

你可能感兴趣的:(2021-02-08【技术】Vue开发之watch监听数组、对象、变量操作分析)