Adding a CSS class to a Vue component with a custom prop

I am looking to create a custom component in Vue that has the following props:

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

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

Below is the .Vue template code 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>

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

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

I would like to add a class to my component based on its prop value.

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

Thank you.

Answer №1

When the value of your icon property is set to home, you can implement class binding in Vue.js using JavaScript expressions within attributes, like shown below:

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

You can also use a shorter syntax:

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

This will result in the following class being applied:

class="fa fa-home"

Answer №2

To include the icon fa-home in your , simply pass it to the parent component like this:

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

You can also use other icons such as fa-plus, fa-bluetooth, etc.

Then, within your component, you can display the icon like so:

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

It may seem a bit confusing as to why the need for the fa class

Make sure to include a prop with a default value of ''

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interactive rotating display with constantly updating information

Recently I started learning angularJS and I must say, I am already hooked. I have developed a website that pulls data from JSON files (created by external scripts) locally to show real-time information on various pages. Now, I want to include a sliding car ...

Navigate to the end in Ionic Vue

In my development of a chat app using Ionic Vue, one challenge I face is ensuring that the latest messages are always visible by automatically scrolling to the bottom. While vue-chat-scroll works well for web applications, it does not seem to be compatibl ...

Double your audio experience with Webaudio by playing the sound twice

While working on WebAudio experimentation, I encountered an issue with loading a sound using the JavaScript code below. function playAudio(){ var audio = document.getElementById('music'); var audioContext = new webkitAudioContext(); ...

When the jQuery Div is moved to the right, it gradually shrinks in size, yet remains unchanged when

I have been making updates to this page, which you can view here. When you select "Let's Get Started" and then proceed with the right arrows, the divs smoothly move to the left without shrinking. However, when clicking on the back or left arrows, the ...

Is it possible for an onclick attribute to assign a function to document.getElementById without overwriting the existing value?

I want to create a numeric keypad in HTML with numbers 1-9, and I'm unsure if JavaScript can handle an onclick function for each key to show the number in the display div. What would be the most effective way to achieve this? <div id="display"> ...

Iterate over each item in the select and include a blank option if either of the elements is missing

Having trouble with 2 drop down menus, select1 and select2. I select item1 from select1 and then click the OK button. But when the selected index is 0 (first option), I want to loop through the items of both drop downs. If the elements at the same index ( ...

An easy way to insert a horizontal line between your text

Currently, I have two text responses from my backend and I'm considering how to format them as shown in the design below. Is it possible to automatically add a horizontal line to separate the texts if there are two or more broadcasts instead of displa ...

JavaScript code that retrieves an array containing only the deleted images from the information obtained from the edit product page

Currently, I am working on an edit product page in react with a node backend. The situation is as follows: Initially, the product had 4 images (a.png, b.png, c.png, d.png). I have made updates by removing the a.png image and adding a new image e.png. So ...

Sorting out conflicts during the compilation of a Vue project

I'm currently facing an issue with compiling my project. I have already attempted this solution, but after deploying my application, the toolbar and some other components lost their base style. Here is my current package.json. "dependencies&quo ...

Infinite loop always occurs with Ui-router FromState being constantly reset

My page is experiencing continuous refreshing and calling $stateChangeStart after the first call to $state.go. I believe this issue may be related to the StateProvider configuration. Can anyone offer suggestions on what might be going wrong? Check out thi ...

Verify if the text field is currently blank or has content before applying attributes

How can I disable one text box if another specific text box is filled within a div containing multiple text boxes? For example: When I enter text in textbox(4), I want to automatically disable textbox(1). And if I remove the text from textbox(4), I want t ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

Transferring data between modules using Ajax or services in React.js

I have a React application where I need to pass data received in one component to another. After receiving the data successfully, I set the state and then try to pass this data as a property to the next component. However, when I try to access this passed ...

The results from utilizing Mongoose's text search feature are inaccurate and not matching the expected

Currently, I am in the process of developing a recipe blog website using Mongoose, Node.js, and Express. However, I have encountered an issue with the text search functionality not producing the desired output. In my Recipe.js schema, I have included spec ...

How to maintain row highlight in jQuery datatable even after it is reloaded

I have a datatable set to reload every 10 seconds. When a user clicks on a row, it highlights, but the highlight is lost when the table reloads. Here is a condensed version of my datatable code: $(document).ready(function() { // set up datatable $(& ...

Delete multiple selected rows from the table

I need help with removing multiple rows from a table. I've tried the code below but it doesn't seem to work. I'm using DataTables v1.10.9. $('#del_Btn').on('click', function () { // 'table' is the instanc ...

Effortlessly fill dropdown menus with data from JSON files

I've been using this jQuery code successfully, but I recently needed to add 3 more field columns to the JSON. My goal is to have the HTML select drop-downs dynamically change based on the data from the previous drop-down. Additionally, my current jQue ...

Learn how to incorporate a custom event listener for Vuetify's v-select component by utilizing directives

My issue involves a v-select element <v-select :items="[1, 2, 3]" label="Some items" v-mydirective ></v-select> Along with the following directive: Vue.directive("mydirective", { bind: function(el, binding) { ...

JavaScript Multiplicative Persistence Problem Resolved by Implementing Efficient Solution that Executes in a Timely

I am currently facing an issue with the following problem: Your task is to create a function called persistence, which takes a positive parameter num and calculates its multiplicative persistence. Multiplicative persistence refers to the number of times y ...

Guide to crafting an effective XHR request using AJAX

Here's a snippet of my basic web page: <!DOCTYPE html> <html> <head> </head> <body onload="start()"> </body> </html> Below is the XMLHttpRequest function I've implemented: function start(){ / ...