广西南宁网站建设google怎么推广
source:这是要监听的数据源,可以是一个 getter 函数、一个 ref 对象、一个 reactive 对象或者一个包含多个数据源的数组。在子组件示例中,() => props.parentValue 就是一个 getter 函数,它返回 props.parentValue 的值,作为 watch 要监听的数据源。
cb:即回调函数,当 source 的值发生变化时会被调用。这个回调函数接收两个参数,分别是新值 newVal 和旧值 oldVal。在子组件示例中,(newVal, oldVal) => { console.log(\值从 ${oldVal} 变为 ${newVal}`); }` 就是这个回调函数。
options:是一个可选的配置对象,可用于设置一些额外的选项,比如 immediate(是否在初始化时立即执行回调)、deep(是否进行深度监听)等。在子组件示例中,{ immediate: false } 就是配置对象,这里设置 immediate 为 false,表示初始化时不立即执行回调。
父组件parent.vue
<template><div><button @click="updateValue">更新值</button><!-- 传递初始值为 null 的 ref 变量给子组件 --><Child :parentValue="parentData" /></div>
</template><script setup>
import { ref } from 'vue';
import Child from './Child.vue';// 初始化 ref 变量为 null
const parentData = ref(null);// 更新 ref 变量的值
const updateValue = () => {parentData.value = '新的值';
};
</script>
子组件 Child.vue
<template><div>接收到的值: {{ parentValue }}</div>
</template><script setup>
import { defineProps, watch } from 'vue';// 声明接收的 props
const props = defineProps({parentValue: {type: null, // 可以接收任意类型default: null}
});// 监听 parentValue 的变化
watch(// source:要监听的数据源,这里是一个 getter 函数() => props.parentValue, // cb:回调函数,当值变化时执行(newVal, oldVal) => {console.log(`值从 ${oldVal} 变为 ${newVal}`);}, // options:配置对象,设置初始化时不立即执行回调{immediate: false }
);
</script>
在这个示例中,watch 函数的使用严格遵循了 watch(source, cb, options) 的形式。