vue3 watch 监听响应式数据变化
2023-09-27 14:27:48 时间
主要是用来监听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 message2 = ref<string>("大满")
watch([message, message2], (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 组件更新之后执行
}
相关文章
- Vue—什么是Vue,怎样配置和搭建Vue3项目
- vue3中retive的错误用法导致数据不跟新
- vue3跟新视图遇见神奇现象
- 40.Vue3:嵌套路由配置
- 36.Vue3:Axios网络请求封装
- vue3函数setUp和reactive函数详细讲解
- vue3-sign 手写签名组件
- 前端笔记(9) Vue3 async await 循环调接口使用案例
- 前端笔记(4) Vue3 全局属性 app.config.globalProperties 使用案例
- vue3:Proxy如何实现响应式?
- vue3:从生命周期开始学习vue3
- Vue3通透教程【十二】TS类型声明优势
- vue3 项目添加 less
- vue3 watch监听单个数据变化
- ❤️[前端学习]大数据全栈工程师之一文快速上手vue3❤️