Vue3 script setup中defineProps与ref值为空的问题排查
问题原因与解决方案
问题出在项目环境不匹配:你使用了Vue 3的<script setup>语法,但当前CodeSandbox项目是Vue 2环境,Vue 2不支持<script setup>,导致props和响应式变量无法被正确解析,所以模板里显示为空。
解决步骤
切换到Vue 3环境
在CodeSandbox中创建新项目时选择「Vue 3」模板,或者在现有项目的依赖面板中,将vue包升级到3.x版本(推荐3.3+),同时更新构建工具(比如替换为Vite,或升级vue-cli到5.x版本)。确认代码正确性
你的代码本身在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
相关产品推荐
相关产品推荐

