Vue 3传递prop时子组件接收失败提示prop未定义如何解决?
核心问题原因
- Prop绑定语法使用错误:你在App组件中使用
:message="Importing"传递Prop时,v-bind(简写为:)会将双引号内的内容当做当前组件的表达式解析,你没有在App组件中定义名为Importing的变量,因此传递给Loading组件的message值为undefined。 - (可选优化问题)Loading组件中将Prop赋值给data属性的写法不合理:data函数只会在组件初始化时执行一次,后续父组件传递的
message发生变更时,loadingText不会同步更新。
修复方案
方案1:传递静态字符串
如果message的值是固定不变的,直接去掉v-bind的冒号,使用静态属性传递即可:
<!-- App组件template --> <template> <Loading message="Importing"></Loading> </template>
方案2:动态绑定字符串字面量
如果后续需要将message的值替换为动态变量,可保留v-bind语法,给字符串加一层单引号,让Vue将其解析为字符串字面量:
<!-- App组件template --> <template> <Loading :message="'Importing'"></Loading> </template>
可选优化
将Loading组件中的loadingText改为计算属性,实现Prop变更时的响应式更新:
<!-- Loading组件script --> <script> export default { name: "Loading", props: ["message"], computed: { loadingText() { return this.message || "Loading" } } } </script>
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

