深入Vue3.2父子组件间ref数组监听机制
在Vue3.2中,利用ref实现父子组件间数据传递和监听是常见场景。本文剖析一个父子组件间ref数组监听的典型问题:为何子组件watch中监听父组件ref数组需要使用箭头函数() => props.tabledata。
问题:父组件通过v-model将ref数组tabledata传递给子组件,子组件需监听tabledata变化并响应。然而,直接在watch中使用props.tabledata无法触发监听函数。
代码示例:
立即学习“前端免费学习笔记(深入)”;
父组件:
<Comp v-model:tabledata="tabledata"></Comp>
import { ref } from 'vue'; export default { setup() { const tabledata = ref([]); const getcommentlist = async () => { const res = await api(); // 模拟异步请求 tabledata.value = res.data; }; return { tabledata, getcommentlist }; } };
子组件:
<script setup> import { defineProps, watch } from 'vue'; const props = defineProps({ tabledata: { type: Array, default: () => [], } }); watch( () => props.tabledata, // 箭头函数为何必要? (newval) => { console.log('tabledata changed:', newval); }, { deep: true } ); </script>
核心问题在于子组件watch的第一个参数。Vue3的watch API要求第一个参数为ref
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才会触发。
以上就是Vue3.2父子组件间ref数组监听:为什么子组件watch中监听父组件ref数组需要使用箭头函数?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号