12

I would like to make a custom component in Vue with the following props:

  • text = text to be displayed in the link.
  • icon = identifier of the icon to be displayed next to the link.

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

I have the following .Vue template for my component.

<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>

Essentially I have the default Font-Awesome code in my template:

<i class="fa fa-home" aria-hidden="true"></i>

and I want add a class to my component by using it's prop.

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

thanks.

2
  • 1
    What do you mean switch out? or what is your expected output? Commented Dec 12, 2017 at 15:04
  • poor choice of wording on my behalf. I'd like to be able to add a class-name to my component with a prop. So, if I wanted my component to show the Bluetooth icon, i'd switch the prop to " icon='fa-bluetooth' " Commented Dec 12, 2017 at 15:07

2 Answers 2

17

So when your property icon is holding the value home you can use some class binding like the following (Thank god js expression are allowed within attributes in Vue.js):

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

or even shorter

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

This will result in

class="fa fa-home"
Sign up to request clarification or add additional context in comments.

Comments

10

If you want to add fa-home to your you can pass it on the parent component like:

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

You can pass other icons like fa-plus, fa-blutooth .... instead

And use it inside your component as:

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

tbh: makes a little sense for me why you need to keep fa

You still need a prop maybe with default value of '' though

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.