我想使用以下 Prop 在 Vue 中制作一个自定义组件:
- text = 要在链接中显示的文本。
- icon = 显示在链接旁边的图标的标识符。
< sidebar-link text="Home" icon="fa-home">
我的组件有以下 .Vue 模板。
<template>
<div id="sidebarItem">
<a href="/index.php">
<div id="sidebarIcon"><i :class="{fa : true}" aria-hidden="true"></i></div>
<div id="sidebarText">{{ text }}</div>
</a>
</div>
</template>
<script>
export default {
props: ['text', 'icon'],
data () {return {}}
}
</script>
本质上,我的模板中有默认的 Font-Awesome 代码:
<i class="fa fa-home" aria-hidden="true"></i>
我想通过使用它的 prop 向我的组件添加一个类。
<sidebar-link text="Home" icon="fa-home"></sidebar-link>
谢谢。
最佳答案
因此,当您的属性 icon
持有值 home
时,您可以像下面这样使用一些类绑定(bind)(谢天谢地,在 Vue.js 中 attributes 中允许使用 js 表达式。 js):
v-bind:class="[{'fa': true}, icon ? 'fa-' + icon : '']"
甚至更短
:class="[{'fa': true}, icon ? 'fa-' + icon : '']"
这将导致
class="fa fa-home"
关于javascript - Vue - 使用 Prop 将类名添加到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47775647/