小言_互联网的博客

vue3 watch 监听响应式数据变化

339人阅读  评论(0)

主要是用来监听ref 或者reactive 所包裹的数据才可以被监听到


  
  1. <template >
  2. < input type = "text" v-model = "message" >
  3. < /template >
  4. <script setup lang = "ts" >
  5. import { ref, watch} from "vue";
  6. let message = ref < string >( "小满")
  7. watch(message, (newVal, oldVal) = > {
  8. console.log(newVal, oldVal)
  9. })
  10. < /script >

 也可以同时监听两个数据源

 


  
  1. <template >
  2. < input type = "text" v-model = "message" >
  3. < input type = "text" v-model = "message2" >
  4. < /template >
  5. <script setup lang = "ts" >
  6. import { ref, watch} from "vue";
  7. let message = ref < string >( "小满")
  8. let message 2 = ref < string >( "大满")
  9. watch([message, message 2], (newVal, oldVal) = > {
  10. console.log(newVal, oldVal)
  11. })
  12. < /script >

ref监听对象需要开启一个属性 deep: true


  
  1. <template >
  2. < input type = "text" v-model = "message.foo.bar.name" >
  3. < /template >
  4. <script setup lang = "ts" >
  5. import { ref, watch} from "vue";
  6. let message = ref({
  7. foo: {
  8. bar: {
  9. name: "小满"
  10. }
  11. }
  12. })
  13. watch(message, (newVal, oldVal) = > {
  14. console.log(newVal, oldVal)
  15. }, {
  16. deep: true
  17. })
  18. < /script >

 但是新的数值和旧的数值会是一样的,

把ref换成 reactive 则无须deep:true,或者开启关闭都是一样的


  
  1. <template >
  2. < input type = "text" v-model = "message.foo.bar.name" >
  3. < /template >
  4. <script setup lang = "ts" >
  5. import {reactive, ref, watch} from "vue";
  6. let message = reactive({
  7. foo: {
  8. bar: {
  9. name: "小满"
  10. }
  11. }
  12. })
  13. watch(message, (newVal, oldVal) = > {
  14. console.log(newVal, oldVal)
  15. }, )
  16. < /script >

 

新的数值和旧的数值也会是一样的

多个数值也是可以监听的到的

 如果想针对单一属性name也是支持的。

 


  
  1. <template >
  2. < input type = "text" v-model = "message.foo.bar.name" >
  3. < /template >
  4. <script setup lang = "ts" >
  5. import {reactive, ref, watch} from "vue";
  6. let message = reactive({
  7. foo: {
  8. bar: {
  9. name: "小满",
  10. age: 18
  11. }
  12. }
  13. })
  14. watch(() = >message.foo.bar.name, (newVal, oldVal) = > {
  15. console.log(newVal, oldVal)
  16. }, )
  17. < /script >
immediate: true 默认开启监听回调

 开启后在没有输入内容的时候会自动回调一次

Flush 三种模式 pre //


  
  1. {
  2. immediate: true,
  3. flush: "pre" / /组件更新之前调用 sync,同步执行,post 组件更新之后执行
  4. }


转载:https://blog.csdn.net/mp624183768/article/details/128756853
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场