在Vue3中,watch中的参数可以分为两部分,即要监听的响应式数据以及回调函数。
语法格式如下:
-
- watch(要监听的响应式数据, 回调函数)
除了以上的两个还有其他的参数
immediate
:是否在初始化时立即执行一次回调函数,默认为false
。deep
:是否深度观察对象或数组的变化,默认为false
。flush
:在触发回调函数之前进行何种操作,默认为"pre"
。可选值有:"pre"(立即更新DOM)、"post"(延迟到队列中的所有回调函数执行完毕后再更新DOM)和"sync"
(在变更时同步应用更改)。onTrigger
:在触发回调函数之前执行的函数。onStop
:当停止观察时执行的函数。lazy
:是否初始不触发回调函数,默认为false
。参数说明:
示例代码:
-
- import { reactive, watch } from 'vue'
- const state = reactive({
- count: 0
- })
- watch(() => state.count, (newValue, oldValue) => {
- console.log('count发生变化:', newValue, oldValue)
- })
- state.count++ // count发生变化: 1 0
-
-
-
-
- import { watch, ref, reactive } from 'vue';
- // 观察一个响应式对象
- const state = reactive({
- name: 'John',
- age: 25,
- });
- watch(() => state.name, (newValue, oldValue) => {
- console.log(`Name changed from ${oldValue} to ${newValue}`);
- });
- // 观察一个ref
- const count = ref(0);
- watch(() => count.value, (newValue, oldValue) => {
- console.log(`Count changed from ${oldValue} to ${newValue}`);
- });
- // 观察一个函数
- watch(
- () => {
- return state.age * count.value;
- },
- (newValue, oldValue) => {
- console.log(`Computed value changed from ${oldValue} to ${newValue}`);
- }
- );
- // 监听多个数据源
- watch([() => state.name, () => count.value], ([newName, newCount], [oldName, oldCount]) => {
- console.log(`Name changed from ${oldName} to ${newName}`);
- console.log(`Count changed from ${oldCount} to ${newCount}`);
- });
- // 配置项示例
- watch(
- () => state.name,
- (newValue, oldValue) => {
- console.log(`Name changed from ${oldValue} to ${newValue}`);
- },
- { immediate: true } // 立即执行回调函数
- );
- 值得注意的是,在Vue3中,watch函数返回一个stop函数,用于停止侦听。你可以使用stop函数来停止之前注册的watch:
-
-
- const stopWatcher = watch(() => state.name, (newValue, oldValue) => {
- console.log(`Name changed from ${oldValue} to ${newValue}`);
- });
- // 停止监听
- stopWatcher();