A guide to dynamically adding a class based on the content of a variable in Vue.js

I have a situation where I need to pass a variable to a component and use it as a class in a div. However, Vue is adding the variable name instead of its content.

So, I am passing the prop color which contains the value red.
Desired outcome:

<div class="red">2</div>

Actual result:
<div class="color">2</div>

I know this might be a beginner question, so please bear with me. If there's a better way to achieve this, I would appreciate the guidance.

Thank you for your help.

Below are my components:

<template>
    <div class="btn btn-outline-primary cell"
         :class="{color}"
         :id="id">
        {{ number }}
    </div>
</template>

<script>
    export default {
        name: "TileElement",
        props: ["id", "number", "color"]
    }
</script>

<style scoped>
    .green {
        color: green;
    }

    .red {
        color: red;
    }

    .yellow {
        color: yellow;
    }

    .cell {
        display: inline-block;
        float: left;
        margin: 0.1em;
        text-align: center;
        background-color: lightgray;
        width: 2.7em;
        height: 2.7em;
    }
</style>

Parent Component:

<template>
    <div class="row">
        <TileElement
                v-for="tile in tiles"
                v-bind:key="tile.id"
                v-bind:number="tile.number"
                v-bind:color="tile.color"
        ></TileElement>
    </div>
</template>

<script>
    import TileElement from './TileElement.vue';

    export default {
        name: "TileRow",
        components: {
            TileElement
        },
        data: function () {
            return {
                tiles: [
                    {id: 1, number: 1, color: "green"},
                    {id: 2, number: 2, color: "red"},
                    {id: 3, number: 3, color: "yellos"}
                ]
            }
        }
    }
</script>

Answer №1

In order to simply pass a class for achieving your goal in a class without any additional conditions or requirements, you have the option of using an array for one or multiple classes:

<div :class="[color]"></div>

However, this is not the only method available.

https://v2.vuejs.org/v2/guide/class-and-style.html

Answer №2

:class="color" is another option that can be used:

var vm = new Vue({
  el: '#app',
  data() {
    return {
      color: 'red'
    };
  }
});
.cell { width: 50px; height: 50px; }
.red { background: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>

<div id="app">
  <div class="cell" :class="color"></div>
</div>

Answer №3

Consider importing the class name dynamically

:class="{[color]: true}"

Answer №4

<div v-for="element in array" :class="'item-'+element">{{ element }}</div>

Here is an example of how to generate a custom class based on the elements in an array using Vue.js

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

In Laravel 7, changing the default guard to "employee" resulted in the issue where the currently authenticated user was returning

In my authentication setup, I made changes to the default guard as shown below: auth.php 'defaults' => [ 'guard' => 'employee', 'passwords' => 'users', ], &a ...

Script on the server side fails to execute following validation of form

Hey there, I'm struggling with my signup form. I want to submit the form using ajax after completing validation. I've used a jQuery plugin for validation, but whenever I click on any field, the ajax request is automatically sent to the server and ...

Utilizing Google Language API for bulk translation tasks

My current project involves using Google's AJAX Language API to translate each element in an array. for(var i=0; i < mytext.length; i++) { google.language.translate(mytext[i], originalLanguage, newLanguage, function(result){ if(!result.error){ ...

Trigger the jQuery Mobile panel menu with a tap on the Android device's native menu button through the utilization of PhoneGap

I am currently in the process of developing an Android app using Jquery Mobile/Phonegap. The main objective is to control the phone's menu button with the following code: <script type="text/javascript" charset="utf-8"> // Execute onDevice ...

Dynamic elements fail to trigger JS function calls

I have a <div> that I dynamically populate with <input> and <a> elements using jQuery. It looks like this: The <div> gets filled when the addServicePanel() function is called: function addServicePanel() { var wrapper = $(".m ...

How to manipulate HTML dynamically in React using Apollo to avoid unnecessary component re-renders

Currently, I am using Apollo's useQuery function to retrieve a user and their posts in my project. The posts are displayed in both a summary view and a detailed view, with the detailed view positioned on top of the summary view. The visibility of the ...

Using the theme object in makeStyles in Material UI without requiring a ThemeProvider – a step-by-step guide!

My custom theme object is structured as follows: import palette from './palette'; import typography from './typography'; const theme = createMuiTheme({ palette, typography, })); export default theme; When using MUI, useStyles() ...

Creating a function with a flexible number of parameters assigned to a variable:

When setting up a Socket.IO client, I have multiple methods structured like the following: myobject.prototype.A = function (callback) { this.foo('a', null, callback); } myobject.prototype.B = function (bar, callback) { this.foo('b&a ...

Replicating a tag and inputting the field content

Scenario: An issue arises with copying a label text and input field as one unit, instead of just the text. Solution Needed: Develop a method to copy both the text and the input field simultaneously by selecting the entire line. Challenge Encountered: Pre ...

Simultaneous Loading: Marvelous Vue Preloader Spinner and Content Display (Vuejs)

Is there a way to ensure that the preloader loads before displaying the content? I tried using the library from , but both the preloader and content load simultaneously. How can I make sure that the preloader loads first, followed by the content? Thank you ...

Is there a way to combine properties from two different objects?

I am working with several JavaScript objects: { x: 5, y: 10, z: 3 } and { x: 7, y: 2, z: 9 } My task is to add these two objects together based on their keys. The resulting object should look like this: { x: 12, y: 12, z: 12 } Do you ...

Picking and modifying a newly added HTML input element using Jquery

I am encountering a problem that I haven't been able to find a solution for through research or Google. I managed to successfully add multiple input boxes to my HTML/JQuery project, which are displaying correctly on the webpage. for (i = 0; i < ma ...

AngularJS form submission with and without page refresh

Looking to implement an AngularJS form directive where, if on /home page, redirect to /search/term and if already on /search page, submit without refreshing the page by simply changing the location. I am able to do both separately, but struggling to writ ...

The NextJs image entered into an endless loop, throwing an error message that said: "The 'url' parameter is correct, but the response from the

I have been using next/image component with next js version ^12.2.3-canary.17 for my current project. The issue I am encountering is that some images are missing from the source directory, resulting in infinite error logs like the one shown below: https:/ ...

Tips for storing mustache templates for rendering in Node.js

My data is stored in the following format: let data = {"list" :[ { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f9fafb8afef0f9f5e8f4fdb6fbf7f5">[email protected] ...

Start the initialization process of the Javascript code for Material Design WEB

Currently, I am utilizing Material Design WEB components in my project. Below are the CSS and JS files that have been included: <head> <link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="styl ...

Troubleshooting Vue.js 2 Routing Issues: Difficulty Accessing Posts Variable

My first venture into Vue.js involves working with WP REST API. Initially, all my posts are displayed perfectly. However, when I attempt to integrate Vue-router, the component responsible for showcasing all the posts, 'home-post-list', breaks do ...

Storing information within a global variable array or exploring alternative methods

I am currently working on a project in electron / node.js and need assistance with the following tasks: Importing data from excel/csv files Visualizing the data using d3.js Cleaning the data by removing duplicates, etc. Using the data for calcu ...

Showing and hiding nested Form Group validation in Angular 4 is a crucial feature that can improve

I have been exploring Angular 4 validation recently. Currently, I am working with a reactive form that contains two radio buttons and two form groups. The behavior I'm trying to achieve is when the user selects the first radio button, it removes valid ...

Performing a search through a string array and updating a specific portion of each string

I am faced with an array containing a long list of Strings, and my goal is to filter out all the strings that begin with 'INSERT ALL' and replace the number inside the parentheses with the string ' NULL' Here is the original array: le ...