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

Vue3/Nuxt3中如何从外部访问组件变量(含script setup)

在Nuxt3中通过<script setup>访问组件内部变量的方法及原理

问题原因

使用<script setup>定义的组件默认是封闭封装的,内部的变量、方法不会自动暴露到组件实例上——这和选项式API的行为不同:选项式API中data、methods等选项里的内容会默认挂载到组件实例,因此能直接通过$refs访问。

实现方式:使用defineExpose编译宏

要让外部能访问<script setup>组件内的变量,必须通过defineExpose主动暴露需要对外开放的内容。

1. 修改子组件(myCompount.vue)

在组件的<script setup>中,用defineExpose将目标变量暴露出去:

<!-- myCompount.vue -->
<script setup>
import { ref } from "vue";
const myString = ref("hi string");

// 显式暴露需要外部访问的变量
defineExpose({
  myString
});
</script>

<template>
  <div>
    <p>{{ myString }}</p>
  </div>
</template>

2. 父页面(myPage.vue)无需修改

原有的代码可以直接访问到暴露的变量,因为组件实例现在包含了myString:

<!-- myPage.vue -->
<script setup>
import myCompount from "./compounts/myCompount.vue";
import { ref, onMounted } from "vue";

const myCompountRef = ref();

onMounted(() => {
  // 现在可以正常访问到myString
  console.log(myCompountRef.value.myString) // 输出: "hi string"
})
</script>

<template>
  <div>
    <myCompount ref="myCompountRef" />
  </div>
</template>

原理说明

  • defineExpose是Vue3专为<script setup>设计的编译宏,它的作用是将指定的属性注入到组件的公共实例中,让外部通过组件ref获取实例时能访问到这些属性。
  • Nuxt3基于Vue3实现,因此这个用法在Nuxt3中完全适用,没有额外的配置要求。
  • 注意:必须在组件挂载完成后(比如onMounted钩子中)访问ref的值,否则组件实例还未初始化,myCompountRef.value会是undefined。

内容的提问来源于stack exchange,提问作者none

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:53:11