vue3.0 监听器

2023年是vue2.0最后一年维护了,更新vue3.0迫在眉睫。

  1. watch监听器可以监听一个getter函数

  • 这个getter要返回一个响应式对象

  • 当该对象更新后,会执行对应的回调函数

import { reactive, watch } from 'vue'
const state = reactive({ count: 0 })
watch(() => state.count, (newValue, oldValue) => {
    // 因为watch被观察的对象只能是getter/effect函数、ref、热active对象或者这些类型是数组
    // 所以需要将state.count变成getter函数
})
  1. watch API 可以直接侦听一个响应式对象,当响应式对象更新后,会执行对应的回调函数

import { ref, watch } from 'vue' 
const count = ref(0) 
watch(count, (count, prevCount) => { 
  // 当 count.value 更新,会触发此回调函数 
})
  1. watch API 可以直接侦听多个响应式对象,任意一个响应式对象更新后,就会执行对应的回调函数。

import { ref, watch } from 'vue' 
const count = ref(0) 
const count2 = ref(1) 
watch([count, count2], ([count, count2], [prevCount, prevCount2]) => { 
  // 当 count.value 或者 count2.value 更新,会触发此回调函数 
})

猜你喜欢

转载自blog.csdn.net/m0_56683897/article/details/128798974