javascript - Vue - 使用 Prop 将类名添加到组件

标签 javascript vue.js vuejs2 vue-component

我想使用以下 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/

相关文章:

javascript - 路由后 Google map 无法在 AngularJS 中工作

javascript 扫雷器 floodfill 算法无法正常工作

javascript - 当循环停止情况增加 1 时,页面停止加载

javascript - Vuetify 步进器垂直和非线性问题

typescript - 如何在带有 Typescript 的 VueJs watch 中使用 Lodash debounce

javascript - Vue/Buefy 的 Datepicker 组件选择了错误的日期

javascript - 没有内容时如何在底部设置页脚

css - Tailwind CSS 响应式断点在 Vue 中不起作用

vue.js - 在 Vue.js 的下拉列表中填充嵌套数组

vue-component - 如何在 VueJS 中的组件之间共享数据