You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:20:37