【问题标题】:Vue - adding a Class-Name to a Component using a propVue - 使用道具向组件添加类名
【发布时间】:2018-05-26 07:36:48
【问题描述】:

我想在 Vue 中使用以下道具制作一个自定义组件:

  • 文本 = 要在链接中显示的文本。
  • icon = 要在链接旁边显示的图标的标识符。

我的组件有以下 .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='fa-bluetooth'”

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

因此,当您的属性 icon 持有值 home 时,您可以使用如下的类绑定(感谢上帝 js 表达式在 Vue.js 中的 attributes 中允许):

v-bind:class="[{'fa': true}, icon ? 'fa-' + icon : '']"

甚至更短

:class="[{'fa': true}, icon ? 'fa-' + icon : '']"

这将导致

class="fa fa-home"

【讨论】:

    【解决方案2】:

    如果您想将 fa-home 添加到您的 中,您可以将其传递给父组件,例如:

    <sidebar-link text="Home" :icon="'fa-home'"></sidebar-link>
    

    您可以传递其他图标,例如 fa-plusfa-blutooth .... 代替

    并在你的组件中使用它:

    <div id="sidebarIcon">
       <i class='fa' :class="icon" aria-hidden="true"></i>
    </div>
    

    tbh:对我来说有点道理为什么你需要保留fa

    你仍然需要一个默认值为'' 的道具

    icon: {
      type: String,
      required: false,
      default: ''
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 2019-12-05
      • 2018-10-01
      • 2021-12-12
      • 2018-10-14
      • 1970-01-01
      相关资源
      最近更新 更多