Vue组合式API中onMounted内子组件ref值为null的问题
问题:onMounted中ref获取子组件为null,但script setup或$refs可正常访问
我搞不懂为什么在onMounted钩子中myComp.value是null,但用<script setup>或者通过$refs访问子组件却能正常工作。
报错信息
- 火狐浏览器:
Uncaught (in promise) TypeError: myComp.value is null - Edge浏览器:
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'rand')
问题代码示例
父组件
<template> <MyComp ref="myComp" /> <h2>{{ myInt }}</h2> </template> <script> import { ref, onMounted } from "vue"; import MyComp from "./MyComp.vue"; export default { components: { MyComp, }, setup() { const myComp = ref(null); const myInt = ref(0); onMounted(() => { myInt.value = myComp.value.rand(); }); return { myInt, }; }, }; </script>
子组件
<template> <h2>Component</h2> </template> <script> export default { setup(_, context) { const rand = () => { return Math.floor(Math.random() * 100); }; context.expose({ rand }); return { rand, }; }, }; </script>
可正常运行的方案
方案1:使用<script setup>
<template> <MyComp ref="myComp" /> <h2>{{ myInt }}</h2> </template> <script setup> import { ref, onMounted } from "vue"; import MyComp from "./MyComp.vue"; const myComp = ref(null); const myInt = ref(0); onMounted(() => { myInt.value = myComp.value.rand(); }); </script>
方案2:通过getCurrentInstance访问$refs
onMounted(() => { let instance = getCurrentInstance(); myInt.value = instance.ctx.$refs["myComp"].rand(); });
问题原因
在选项式API的setup函数中,你定义的myComp ref没有被返回出去,Vue无法将模板中的ref="myComp"和这个变量建立关联,导致myComp.value始终为null。
而<script setup>会自动将所有顶层声明的变量暴露给模板,所以myComp能被正确关联到子组件的ref;通过getCurrentInstance访问$refs是直接从组件实例上获取引用,绕开了setup返回值的关联逻辑,因此也能正常工作。
解决方法
在选项式API的setup函数中,把myComp加入返回对象,让Vue建立模板ref和变量的关联即可:
setup() { const myComp = ref(null); const myInt = ref(0); onMounted(() => { myInt.value = myComp.value.rand(); }); return { myInt, myComp // 必须返回该ref变量 }; }
内容的提问来源于stack exchange,提问作者jdson
相关产品推荐
相关产品推荐

