5.Vue3 Watch侦听器

108 阅读1分钟

1.watch侦听器

<template>
  第一个值:
  <input v-model="msg1" type="text"/><br/>
  第二个值:
  <input v-model="msg2" type="text"/><br/>
  测试深度监听:
  <input v-model="person.car.carName" type="text">
</template>

<script setup lang="ts">
import {Ref, ref, watch} from "vue";

const msg1: Ref<string> = ref<string>('')

const msg2: Ref<string> = ref<string>('')

const person = ref({
  name: 'Yang',
  age: 23,
  car: {
    carName: 'Mi',
    color: 'blue'
  }
})

// 侦听数据的变化
watch(msg1, (newValue, oldValue) => {
  console.log('新值=>', newValue)
  console.log('旧值=>', oldValue)
})

// 侦听多个源
watch([msg1, msg2], (newValue, oldValue) => {
  console.log('新值=>', newValue) // 此时新值旧值会被数组收集起来 按照监听的顺序 第一个为msg1 第二个为msg2
  console.log('旧值=>', oldValue)
})

// 深度监听
// 通过ref处理的对象使用watch要监听value值 才能正常监听 否则要加deep
// 通过reactive处理的对象可以正常监听到
watch(person, (newValue, oldValue) => {
  console.log('新值=>', newValue) // 此时新值旧值会被数组收集起来 按照监听的顺序 第一个为msg1 第二个为msg2
  console.log('旧值=>', oldValue)
}, {
  deep: true, // 深度监听
  immediate: true // 开始就执行一次
})
</script>

2.watchEffect 高级侦听器

<template>
  <input id="ipt" v-model="msg1" type="text"/><br/>
  <input v-model="msg2" type="text"/><br/>
</template>

<script setup lang="ts">
import {ref, watchEffect} from "vue";

let msg1 = ref<string>('hello')

let msg2 = ref<string>('hi')

// 1.进页面自动调用一次
// 2.直接在函数中写需要的值就行了
// 3.清除副作用
watchEffect((before) => {
  // 获取一个元素
  const ipt: HTMLInputElement = document.querySelector('#ipt') as HTMLInputElement
  console.log(ipt) // 会发现为null 需要配置
  console.log(msg1.value)
  console.log(msg2.value)
  before(() => {
    console.log('先调用这个,在执行其他')
  })
}, {
  flush: 'post',  // pre 组件更新前执行  sync 强制效果始终同步触发 post 组件更新后执行
  // 提供了一个调试用的函数
  onTrigger: (e) => {
    debugger
  }
})
</script>