基本用法
watch
有三个参数
第一个参数是监听源
第二个参数回调函数cb(newVal,oldVal)
第三个参数一个options
配置项
- 监听单个属性
<template>
<div>姓:<input v-model="lastName" type="text" /></div>
<div>名:<input v-model="firstName" type="text" /></div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
let firstName = ref('三')
let lastName = ref('张')
watch(lastName, (newVal, oldVal) => {
console.log(newVal, oldVal)
})
</script>
- 监听多个属性值,用数组
<script setup lang="ts">
import { ref, watch } from 'vue'
let firstName = ref('三')
let lastName = ref('张')
watch([lastName, firstName], (newVal, oldVal) => {
// 这样输出也会是数组,一一对应关系
console.log(newVal, oldVal)
})
</script>
- 当对象层级过深时,
ref
包裹的对象需要开启deep
深度监听,不然无法监听到,reactive
不需要
<template>
<div>title:<input v-model="message.foo.bar.name" type="text" /></div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
let message = ref({
foo: {
bar: {
name: 'hhh'
}
}
})
watch(
message,
(newVal, oldVal) => {
console.log(newVal, oldVal)
},
{
deep: true
}
)
</script>
但是这时监听到的新值与旧值是一样的
通过设置用函数来获取监听值,可以解决上述问题
<script setup lang="ts">
import { ref, watch } from 'vue'
let message = ref({
foo: {
bar: {
name: 'hhh'
}
}
})
watch(
() => message.value.foo.bar.name,
(newVal, oldVal) => {
console.log(newVal, oldVal)
}
)
</script>
options配置项
-
deep
用于开启深度监听,解决层级过深监听不到 -
immediate
在侦听器创建时立即触发回调。第一次调用时旧值是 undefined
<script setup lang="ts">
import { ref, watch } from 'vue'
let message = ref({
foo: {
bar: {
name: 'hhh'
}
}
})
watch(
() => message.value.foo.bar.name,
(newVal, oldVal) => {
// hhh undefined
console.log(newVal, oldVal)
},
{
immediate: true
}
)
</script>
- flush
- pre — 组件更新之前调用(默认)
- sync — 同步执行
- post — 组件更新之后调用