watch第一个参数监听源
watch第二个参数回调函数cb(newVal,oldVal)
watch第三个参数一个options配置项是一个对象{
immediate:true //是否立即调用一次
deep:true //是否开启深度监听
}
<template>
<div>
case1:<input v-model="message1" type="text" id="1">
<span>{{message1}}span>
div>
template>
<script setup lang="ts">
import { ref, watch } from 'vue'
let message1=ref<string>('12');
watch(message1, (newVal, oldVal) => {
console.log('新的值----', newVal);
console.log('旧的值----', oldVal);
},{
immediate:false,
deep:true
})
script>
<style>
style>
<template>
<div>
case1:<input v-model="message1" type="text">
<span>{{message1}}span>
<hr>
case2:<input v-model="message2" type="text"><span>{{message2}}span>
div>
template>
<script setup lang="ts">
import { ref, watch } from 'vue'
let message1=ref<string>('12');
let message2=ref<string>('34');
watch([message1,message2], (newVal, oldVal) => {
console.log('新的值----', newVal);
console.log('旧的值----', oldVal);
},{
immediate:false,
deep:true
})
script>
<style>
style>
<template>
<input type="text" v-model="message.nav.bar.name">
template>
<script setup lang="ts">
import { ref, watch,reactive } from 'vue'
let message=reactive({
nav:{
bar:{
name:""
}
}
})
watch(message,(newVal,oldVal)=>{
console.log(newVal,oldVal);
})
script>
<style>
style>
let message=reactive({
nav:{
bar:{
name:""
}
}
})
watch(()=>message.nav.bar.name,(newVal,oldVal)=>{
console.log(newVal,oldVal);
})
<template>
<h2>姓名:{{ Person.name }}h2>
<button @click="Person.name += '~'">修改button>
<button @click="stop">停止button>
template>
<script setup lang="ts">
import { ref, watch, reactive, watchEffect } from 'vue'
const Person = reactive({
name: '张三'
})
//监听御前清理oninvalidate参数,加上stop后停止监听
const stop=watchEffect((oninvalidate) => {
oninvalidate(() => {
console.log("before");
});
Person.name
console.log('姓名发送了变化'+Person.name);}
,{
flush:"sync",//pre:组件更新前执行 sync:强制效果始终同步触发 post:组件更新后执行
onTrigger () {
console.log("我是onTrigger")
}
})
script>
<style>
style>
运行结果:点击停止button后,将不会监听Person.name的变化,控制台也不会打印出person.name结果。