Vue学习之路11----侦听器

watch

Vue3中的watch只能监视以下4种数据:

  1. ref定义的数据
  2. reactive定义的数据
  3. 函数返回一个值(getter函数)
  4. 一个包含上述内容的数组
1.监听基本类型数据

​ watch可以监视变量的变化并基于该变化做出响应,也可以关闭此侦听器,注意,你不能监听变量的属性值

<template>
  <div>{{ num }}</div>
  <button @click="num++">add</button>
</template>
<script setup name="App">
  import { ref, watch } from "vue";
  let num=ref(0)
  const stopWatch=watch(num,(newValue,oldValue)=>{
    console.log('num变化了',newValue,oldValue);
    if(newValue>=10){
      stopWatch()
    }
  })
</script>
<style scoped></style>

请添加图片描述

2.监听对象类型数据
<template>
  <div>{{ obj1.num }}</div>
  <button @click="obj1.num++">add</button>
  <button @click="changec1">修改c1</button>
</template>
<script setup name="App">
  import { ref,reactive, watch, } from "vue";
  let obj1=reactive({
    num:0,
    car:{
      c1:'奔驰',
      c2:'宝马'
    }
  })
  function changec1() {
    obj1.car.c1='兰博基尼'
  }
  // 监视整个对象:ref或reactive
  // ref需要深度监视对象的属性值需要deep:true,reactive则不需要,它默认是deep:true
  // 加上immediate可以在挂载前就执行一次watch
  watch(obj1,(newValue,oldValue)=>{
    console.log('obj变化了',newValue,oldValue);
  },{deep:true,immediate:true})
  // 监视对象的某个属性:基本类型需要写成getter函数,对象类型则不需要,只能用reactive
  watch(()=>obj1.num,(newValue,oldValue)=>{
    console.log('obj.num变化了',newValue,oldValue);
  })
  watch(obj1.car,(newValue,oldValue)=>{
    console.log('obj.car变化了',newValue,oldValue);
  })
</script>
<style scoped></style>

请添加图片描述

3.监听多个数据

​ 一般使用数组监听多个数据

<template>
  <div>{{ obj1.num }}</div>
  <button @click="obj1.num++">add</button>
  <button @click="changec1">修改c1</button>
</template>
<script setup name="App">
  import { ref,reactive, watch, } from "vue";
  let obj1=reactive({
    num:0,
    car:{
      c1:'奔驰',
      c2:'宝马'
    }
  })
  function changec1() {
    obj1.car.c1='兰博基尼'
  }
  watch([()=>obj1.num,obj1.car],(newValue,oldValue)=>{
    console.log('obj变化了',newValue,oldValue);
  })
</script>
<style scoped></style>

请添加图片描述

4.watchEffect

​ watchEffect不需要指定监听哪个数据

<template>
  <div>{{ obj1.num }}</div>
  <button @click="obj1.num++">add</button>
</template>
<script setup name="App">
  import { ref,reactive, watchEffect, } from "vue";
  let obj1=reactive({num:0})
  watchEffect(()=>{
    if (obj1.num>=5) {
      console.log('响应');      
    }
  })
</script>
<style scoped></style>

请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值