
深入Vue3.2父子组件间ref数组监听机制
在Vue3.2中,利用ref实现父子组件间数据传递和监听是常见场景。本文剖析一个父子组件间ref数组监听的典型问题:为何子组件watch中监听父组件ref数组需要使用箭头函数() => props.tabledata。
问题:父组件通过v-model将ref数组tabledata传递给子组件,子组件需监听tabledata变化并响应。然而,直接在watch中使用props.tabledata无法触发监听函数。
代码示例:
立即学习“前端免费学习笔记(深入)”;
父组件:
import { ref } from 'vue';
export default {
setup() {
const tabledata = ref([]);
const getcommentlist = async () => {
const res = await api(); // 模拟异步请求
tabledata.value = res.data;
};
return { tabledata, getcommentlist };
}
};
子组件:
核心问题在于子组件watch的第一个参数。Vue3的watch API要求第一个参数为ref或() => T类型的函数。
props.tabledata本身是ref对象,而非简单数组,它是一个响应式对象,包含value属性持有实际数组数据。直接使用props.tabledata,watch不会监听其内部value属性的变化。
箭头函数() => props.tabledata的作用是返回props.tabledata的当前值。watch监听此函数返回值的变化,间接监听tabledata.value的变化。只有tabledata.value改变时,箭头函数返回值才改变,触发watch回调。
更简洁高效的方案:
在子组件中,可直接使用props.tabledata.value作为watch参数,并设置deep: true:
watch(
() => props.tabledata.value,
(newval) => {
console.log('tabledata changed:', newval);
},
{ deep: true }
);
或更推荐的写法,直接监听props.tabledata,watch会自动追踪ref对象的变化:
watch(
props.tabledata,
(newVal) => {
console.log('tableData changed:', newVal);
},
{ deep: true }
);
关键:deep: true选项确保watch检测数组内部元素的变化。 缺少deep: true,只有当整个tabledata.value数组被替换时,watch才会触发。









