主要是用来监听ref 或者reactive 所包裹的数据才可以被监听到
-
<template
>
-
<
input
type
=
"text" v-model
=
"message"
>
-
<
/template
>
-
<script setup lang
=
"ts"
>
-
-
-
import {
ref, watch}
from
"vue";
-
-
let message
=
ref
<
string
>(
"小满")
-
watch(message, (newVal, oldVal)
=
> {
-
console.log(newVal, oldVal)
-
})
-
<
/script
>
也可以同时监听两个数据源
-
<template
>
-
<
input
type
=
"text" v-model
=
"message"
>
-
<
input
type
=
"text" v-model
=
"message2"
>
-
<
/template
>
-
<script setup lang
=
"ts"
>
-
-
-
import {
ref, watch}
from
"vue";
-
-
let message
=
ref
<
string
>(
"小满")
-
let message
2
=
ref
<
string
>(
"大满")
-
watch([message, message
2], (newVal, oldVal)
=
> {
-
console.log(newVal, oldVal)
-
})
-
<
/script
>
ref监听对象需要开启一个属性 deep: true
-
<template
>
-
<
input
type
=
"text" v-model
=
"message.foo.bar.name"
>
-
<
/template
>
-
<script setup lang
=
"ts"
>
-
-
-
import {
ref, watch}
from
"vue";
-
-
let message
=
ref({
-
foo: {
-
bar: {
-
name:
"小满"
-
}
-
}
-
})
-
watch(message, (newVal, oldVal)
=
> {
-
console.log(newVal, oldVal)
-
}, {
-
deep:
true
-
})
-
<
/script
>
但是新的数值和旧的数值会是一样的,
把ref换成 reactive 则无须deep:true,或者开启关闭都是一样的
-
<template
>
-
<
input
type
=
"text" v-model
=
"message.foo.bar.name"
>
-
<
/template
>
-
<script setup lang
=
"ts"
>
-
-
-
import {reactive,
ref, watch}
from
"vue";
-
-
let message
= reactive({
-
foo: {
-
bar: {
-
name:
"小满"
-
}
-
}
-
})
-
watch(message, (newVal, oldVal)
=
> {
-
console.log(newVal, oldVal)
-
}, )
-
<
/script
>
新的数值和旧的数值也会是一样的
多个数值也是可以监听的到的
如果想针对单一属性name也是支持的。
-
<template
>
-
<
input
type
=
"text" v-model
=
"message.foo.bar.name"
>
-
<
/template
>
-
<script setup lang
=
"ts"
>
-
-
-
import {reactive,
ref, watch}
from
"vue";
-
-
let message
= reactive({
-
foo: {
-
bar: {
-
name:
"小满",
-
age:
18
-
}
-
}
-
})
-
watch(()
=
>message.foo.bar.name, (newVal, oldVal)
=
> {
-
console.log(newVal, oldVal)
-
}, )
-
<
/script
>
immediate: true 默认开启监听回调
开启后在没有输入内容的时候会自动回调一次
Flush 三种模式 pre //
-
{
-
immediate:
true,
-
flush:
"pre"
/
/组件更新之前调用
sync,同步执行,post 组件更新之后执行
-
}
转载:https://blog.csdn.net/mp624183768/article/details/128756853
查看评论