Vue3未传值时prop默认值不显示,原因何在?
问题:Vue组件prop默认值未生效,页面无内容显示
你写的这段Vue 3 + TypeScript代码中,未传入myProp时本该显示默认值"test",但页面什么都不显示,原因很明确:
- 你错误地把
default写在了TypeScript的类型定义里,Vue 3的TS类型声明式defineProps只负责类型校验,根本不会识别类型结构里的default属性。 - 因为没正确设置默认值,父组件不传
myProp时,props.myProp就会是undefined,页面自然没内容输出。
修正后的代码
<template> <div> {{ propValue }} </div> </template> <script setup lang="ts"> import { defineProps, withDefaults } from "vue" // 用withDefaults包裹defineProps,单独设置默认值 const props = withDefaults(defineProps<{ myProp?: string // 标记为可选属性 }>(), { myProp: "test" // 在这里指定默认值才会生效 }) const propValue = props.myProp </script>
内容的提问来源于stack exchange,提问作者drake035
相关产品推荐
相关产品推荐

