Vue.js中Prop传递后属性绑定失效?如何正确绑定Prop到属性
Vue组件Prop绑定问题:href和style属性无法解析
问题出在属性绑定的语法错误:Vue中,元素属性不能用{{}}文本插值来绑定,这种语法只适用于元素的内容区域(比如你写的{{ title }})。属性绑定必须使用v-bind指令(或简写:),否则{{ href }}和{{ style }}会被当作普通字符串直接输出,不会被Vue解析。
修正后的Button.vue代码
只需要修改模板部分的属性绑定方式:
<script setup lang="ts"> defineProps({ href: String, title: String, alt: String, style: String }) </script> <template> <!-- 用:(v-bind简写)绑定属性 --> <a :href="href"> <button :class="style">{{ title }}</button> </a> </template>
优化建议(可选)
你当前用style作为Prop名,容易和原生的style属性混淆,建议重命名为更清晰的名称,比如btnClass:
父组件Top.vue修改:
<script setup lang="ts"> import Button from './Button.vue' </script> <template> <div class="flex"> <Button href="test" title="Home" alt="To home" btn-class="top" /> </div> </template>
子组件Button.vue修改:
<script setup lang="ts"> defineProps({ href: String, title: String, alt: String, btnClass: String }) </script> <template> <a :href="href"> <button :class="btnClass">{{ title }}</button> </a> </template>
修改后就能得到你期望的渲染结果:
<a href="test"><button class="top">Home</button></a>
内容的提问来源于stack exchange,提问作者Player_X_YT
相关产品推荐
相关产品推荐

