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

如何将Vue3 Script Setup中的变量值传递至其他文件的Template?

解决Vue3跨文件使用Script Setup中定义的文本变量问题

场景1:变量存放在单独的JS/TS文件中

如果文本变量在单独的文件(比如src/assets/texts.js)里定义,需用ES模块语法正确导出:

// src/assets/texts.js
export const welcomeText = '欢迎使用本应用';
export const buttonLabel = '点击提交';

在目标Vue组件中导入并直接在模板使用:

<!-- src/components/TargetComponent.vue -->
<script setup>
import { welcomeText, buttonLabel } from '@/assets/texts.js';
</script>

<template>
  <div>
    <h1>{{ welcomeText }}</h1>
    <button>{{ buttonLabel }}</button>
  </div>
</template>

场景2:变量存放在另一个Vue组件的Script Setup中

若变量在某个Vue组件的Script Setup里定义,必须通过defineExpose暴露变量,才能被其他组件访问:

<!-- src/components/SourceComponent.vue -->
<script setup>
const titleText = '页面标题';
const descText = '这是一段描述文本';

// 暴露变量给父组件/其他组件
defineExpose({
  titleText,
  descText
});
</script>

在目标组件中通过组件实例引用这些变量:

<!-- src/components/TargetComponent.vue -->
<script setup>
import { ref } from 'vue';
import SourceComponent from '@/components/SourceComponent.vue';

const sourceRef = ref(null);
</script>

<template>
  <SourceComponent ref="sourceRef" />
  <div>
    <h2>{{ sourceRef.titleText }}</h2>
    <p>{{ sourceRef.descText }}</p>
  </div>
</template>

常见排查点

  • 检查导入路径:用@/开头需确保项目配置了路径别名,或改用相对路径(比如../assets/texts.js)
  • 确认导出方式:单独文件要加export,Vue组件内必须用defineExpose暴露变量
  • 核对变量名:模板中引用的变量名要和导出的完全一致(区分大小写)
  • 异步组件场景:需确保组件加载完成后再访问变量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:14:59