
深入解析Vue3中ref数组在父子组件通信中的监听失效问题
在Vue3应用开发中,父子组件间高效的数据传递至关重要。本文将深入探讨使用ref数组进行父子组件通信时,监听失效的常见问题,并提供有效的解决方案。
问题描述:
父组件通过v-model将一个ref类型的数组tabledata传递给子组件。子组件需要监听tabledata的变化,并在数据更新时执行相应操作。然而,子组件中watch函数的写法却影响了监听效果。
立即学习“前端免费学习笔记(深入)”;
代码示例:
父组件:
<Comp v-model:tabledata="tabledata"></Comp>
import { ref } from 'vue';
import api from './api'; // 假设的API调用
export default {
setup() {
const tabledata = ref([]);
const getcommentlist = async () => {
const res = await api();
tabledata.value = res.data;
};
return { tabledata, getcommentlist };
},
};子组件:
<script setup>
import { watch, ref, onMounted } from 'vue';
const props = defineProps({
tabledata: {
type: Array,
default: () => [],
},
});
watch(
() => props.tabledata, // 监听失效的写法
(newVal) => {
console.log('tabledata changed:', newVal);
},
{ deep: true },
);
</script>问题在于子组件watch函数的第一个参数使用了() => props.tabledata的形式,导致监听失效。如果直接使用props.tabledata,则监听能够正常工作。
问题解答:
根据Vue3的watch API文档,第一个参数watcherSource可以是ref<t></t>或() => T。
ref<t></t>代表一个响应式ref对象。() => T代表一个返回T类型值的函数。当直接使用props.tabledata时,它指向父组件传递的ref对象,符合ref<t></t>类型,watch可以正确监听tabledata的变化。
而使用() => props.tabledata时,watch监听的是这个getter函数的返回值,而非ref对象本身。每次函数执行都返回tabledata的当前值,但watch无法追踪返回值的响应式变化,因此监听失效。
正确的写法:
为了监听ref数组的变化,子组件的watch应该直接使用props.tabledata作为第一个参数,并设置deep: true选项以监听数组内部元素的变化:
<script setup>
import { watch } from 'vue';
const props = defineProps({
tabledata: {
type: Array,
default: () => [],
},
});
watch(
props.tabledata,
(newVal) => {
console.log('tabledata changed:', newVal);
},
{ deep: true },
);
</script>通过以上修改,子组件可以正确监听父组件tabledata的任何变化,包括数组元素的增删改。 记住,deep: true选项对于监听数组内部元素的变化至关重要。 如果不需要监听数组内部元素的变化,可以移除deep: true。
以上就是Vue3父子组件通信:ref数组监听失效的原因是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号