vue watch监听vuex数据(vue3 watch 监听响应式数据变化)
导读:主要是用来监听ref 或者reactive 所包裹的数据才可以被监听到 <...
主要是用来监听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 组件更新之后执行 }创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!