Using Vue.js: applying a CSS class to a child element within a component

Is it possible to insert a class into a component class tag from the HTML file? For instance, if we have a component like the one below and want to replace the icon field with whatever is used in the HTML file.

Sample code from MyButton.vue file:

<template>
  <component :is="type" href="href" class="button btn">
      <i class="fa fa-lg" :class="[icon]"></i>
  </component>
</template>


<script>
  export default {
    props: {
      href: {
        type: String,
        default: null
      },
      to: {
        type: String,
        default: null
      },
      icon: {
        type: String,
        default: null
      }
    },
    computed: {
      type() {
        if (this.href) {
          return 'a'
        } else {
          return 'button'
        }
      }
    }
  }
</script>

In our app.js file:

Vue.component('my-button', require('./components/MyButton.vue').default);

In the HTML file:

<my-button class="fa-save"></my-button>

The desired output should be something like:

<a type="button" class='button btn'><i class="fa fa-lg fa-close "></i></a>

Answer №1

One way to connect props with HTML attributes is by directly binding them.

If we look at MyButton.vue:

<i class="fa fa-lg" :class="[icon]"></i>

Alternatively, you can simply pass the prop icon as a string.

<i class="fa fa-lg" :class="icon"></i>

In order for this to work, remember to pass the props to the component caller like this:

<my-button icon="fa-close"></my-button>

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

Issue: Actions should be in the form of plain objects. However, the given type is 'Promise'. To resolve this, consider incorporating middleware into your React Native store

Currently, I am facing an issue while trying to retrieve products from Firebase. Despite having redux-thunk installed to manage promises and using middleware in my store, I encountered the following error: Actions must be plain objects. The actual type d ...

What's the best way to modify HTML element classes using Javascript?

I have designed a custom cms theme with various customization options that I wish to showcase in a live demo. My goal is to implement Javascript style switchers or modifiers where users can choose values from checkboxes or select tags, and see their select ...

Vuetify's paginated server-side datatable does not support client-side sorting

The Challenge The issue I am facing revolves around using a server-side paginated datatable. Specifically, when utilizing the Vuetify data tables component and attempting to perform client-side sorting due to using a public API that I did not develop, the ...

Mastering the art of utilizing callback functions

As a newcomer to Javascript and Jquery, I am still learning the basics. One thing that confuses me is how javascript executes each line as it encounters it. In a certain scenario (when my value is greater than 9), the custom alert will trigger and the wind ...

How to refresh a page in React when the browser's back button is pressed

In my React project using Material-UI, I have created a simple search form. On page A, users can input values in text boxes and select options from drop-down lists and checkboxes. The results are then displayed on page B. My issue arises when returning to ...

Having difficulty invoking a JavaScript function through PHP

My goal is to achieve the following: <html> <script type="text/javascript" src="jquery.js"></script> <a id="random">before</a> <script> function test(a) { document.getElementById('random').innerHTM ...

Dividing large pages into smaller components

In the realm of code styles, I am faced with a question specific to Vue.js as that is the framework I am utilizing for my front end development. As I dive into building a complex web application with Vue.js, even with the use of single file components, I ...

Concatenate a variable to the conclusion of a string using PHP

Currently, I am trying to include the id of the logged-in user in a table name. For instance, I would like to have a table named Rating_User_1 where 1 corresponds to the id of the user who is currently logged in. I have stored the user's id in a varia ...

How can I use Laravel to enter data using the post method?

I've been struggling with data transfer in my Angular component for a while now, specifically using a post method. Despite extensive research and reading various documents, I haven't been able to find a solution. Can you assist me with this issue ...

Pass information from JavaScript to PHP without using a form

I am trying to pass data from JavaScript to PHP without using an HTML form. The scenario involves the user clicking on a specific HTML div, sending its ID to a JavaScript file, and then transferring it back to a PHP file. How can I achieve this? Below is ...

Searching for paired values within an array using Javascript or Jquery

In my JavaScript code, I am working with an array called ppts that looks like: var ppts = []; //... ppts.push({x: mouse.x, y: mouse.y}); //... var tmpArr = []; for (var i=1;ppts.length-1; i++) tmpArr.push(ppts[i].x); alert(tmpArr[2]); tmp_ctx.lineTo(pars ...

JavaScript counter that starts at 1 and increments with each rotation

I am working with an array of image IDs. let images = ['238239', '389943', '989238', ... ]; let max = images.length; The array begins at index 0 and its size may vary. For instance, if there are 5 images in the array, the i ...

Transformation of JSON output from the controller into a sophisticated entity: Razor

I have a partial view called "_SearchPanel" which includes a dropdown list for selecting years, a multiselect control for classes (along with some other drop downs - omitted), and a search button. My goal is to only refresh/update the classes list when ch ...

SQLSTATE[23000]: Data integrity violation: 1452 Unable to insert or modify a child record: the foreign key relationship is not satisfied

I am encountering an issue with the database while trying to save data from a form into the reply_qs table. The error message displayed is as follows: ERROR: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a ...

Exploring nested objects within Vue components

Is there a way to access the arrays of objects branches and report in the response when I only have access to currentView and subTask, but not subTasks2? I am following the same approach, but can't seem to access those specific elements. Any guidance ...

Error: Type Error - 'style' is not defined in the Progress Bar Project

Having recently started learning Javascript, I have been engaging with various tutorials and projects in order to gain familiarity with the language. One particular tutorial that caught my attention is a Progress-Bar tutorial by "dcode" available at this l ...

Tips for accessing and displaying JSON data using jQuery

Data in JSON format: [ { "ID":"25", "Serial":"1", "Purchase_id":"8", "Item":"23", "Unit":"1", "HSN":"84212120", "Quantity":"10", "Purchase_rate":"100", ...

Issue: React error message indicates that the .map() function is not recognized. The API response is in the form of an object, making

As a newcomer to REACT.JS, I am currently facing the challenge of extracting data from an API for my project. Utilizing "Axios" for sending the get request, I have encountered a situation where the response comes back as an array in one API and as an objec ...

Creating expandable card components with React and CSS using accordion functionality

I am currently working on creating a card that will expand its blue footer when the "view details" link is clicked to show lorem text. However, I am encountering an issue where the blue bottom of the card does not expand along with the lorem text. You can ...

Warning: Typescript is unable to locate the specified module, which may result

When it comes to importing an Icon, the following code is what I am currently using: import Icon from "!svg-react-loader?name=Icon!../images/svg/item-thumbnail.svg" When working in Visual Studio Code 1.25.1, a warning from tslint appears: [ts] Cannot ...