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

Vue3 script setup中defineProps与ref值为空的问题排查

问题原因与解决方案

问题出在项目环境不匹配:你使用了Vue 3的<script setup>语法,但当前CodeSandbox项目是Vue 2环境,Vue 2不支持<script setup>,导致props和响应式变量无法被正确解析,所以模板里显示为空。

解决步骤

  1. 切换到Vue 3环境
    在CodeSandbox中创建新项目时选择「Vue 3」模板,或者在现有项目的依赖面板中,将vue包升级到3.x版本(推荐3.3+),同时更新构建工具(比如替换为Vite,或升级vue-cli到5.x版本)。

  2. 确认代码正确性
    你的代码本身在Vue 3环境下是完全有效的:

    • <script setup>中通过defineProps声明的props可以直接在模板中使用
    • ref创建的响应式变量也能直接在模板中访问,无需额外解构或转换

验证用的HelloWorld.vue代码(无需修改)

<template>
  <div class="hello">
    <h1>START</h1>
    <p>msg: "{{ msg }}"</p>
    <p>name: "{{ name }}"</p>
    <h1>END</h1>
  </div>
</template>

<script setup>
import { defineProps, ref } from "vue";

const props = defineProps({
  msg: String,
});

const name = ref("This is my name");
</script>

验证用的App.vue代码(无需修改)

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Hello There!" />
</template>

<script>
import HelloWorldVue from "./components/HelloWorld.vue";
export default {
  name: "App",
  components: {
    HelloWorld: HelloWorldVue,
  },
};
</script>

切换到Vue 3环境后,模板就能正常渲染msg和name的值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 06:21:57