Creating conditional classes in VUE is a simple process that can greatly improve the organization

Is it possible to use Vue conditions to dynamically add classes based on the text content in the DOM?

Let's say I have a list of color names:

<span>yellow</span>
<span>red</span>
<span>grey</span>

I would like to create a condition where if the text content is "yellow", then add the class 'color_yellow', and so on for other colors.

Answer №1

Here is a sample code snippet that you can try:

new Vue({
  el: '#demo',
  data() {
    return {
      colors: ['yellow', 'red', 'grey']
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
.color_yellow {
  color: yellow;
}
.color_red {
  color: red;
}
.color_grey {
  color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <ul>
    <li v-for="(color, i) in colors" :key="i">
      <span :class="`color_${color}`">{{ color }}</span>
    </li>
</div>

Answer №2

If you're looking to experiment with colors, give this a go

<span :class="color.colorName">{{ color.colorName }}</span>

When it comes to styling in css,

.yellow { color: yellow }
.red { color: red }

For further information, feel free to visit https://v2.vuejs.org/v2/guide/class-and-style.html

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

Outer div encapsulating inner div within its boundaries

I am looking for a solution where the inner div stays fully contained within the outer div, without overflowing and overlapping with the padding of the outer div. Here is a code sample that demonstrates the issue .inner { /* Overflow */ overflow-wra ...

Using jQuery to easily transfer the direct image URL from an input field to a designated div element

In order to enhance the learning experience of 8th-grade chemistry students studying the periodic table of elements, I am working on a project that involves creating an "Augmented Reality" tool. The goal is to allow students to input a direct URL for an im ...

The code to activate a checkbox through jQuery is not functioning as expected

Here is a JavaScript function that I've been working with: const bindSwitches = function() { $(document).on("click", ".lever", function() { var checkbox = $(this).siblings("input[type=checkbox]"); var hiddenFiel ...

The function HandleKeyPress is failing to recognize the input from the down arrow

I'm currently working on developing a customized and user-friendly select input using React.js. My goal is to have the functionality where the up and down arrow keys behave like the tab key within the context of selecting options. In order to achieve ...

Array of Javascript elements in three dimensions

Currently, I am working on creating a 3D array in JavaScript, but I am facing some uncertainty in the process. My goal is to have three arrays - Provinces, Cities, and Malls - all in a sequential order, and I am looking to build a 3D array to store all thi ...

How to properly format credit card input using JavaScript or jQuery

I need to implement a feature where users input their credit card information, and once they complete the form, I want to display the credit card number in this format: xxxxxxxxxxxx1111 or xxxx-xxxx-xxxx-1111, without altering the actual input value. Is ...

Utilizing Vue and Nuxt.js to Implement Dynamic Active Class on Parent Menu with Bootstrap Navbar

I'm just getting started with vue + nuxt.js Using a bootstrap navbar. Check out this link This is the code I have: <b-nav-item-dropdown type="dark"> <template slot="button-content"> <i class="fas fa-user" ...

Display chart labels are constantly visible in Vue Chart JS

In my Vue.js JavaScript application, I am working on setting up a chart where I want the labels and chart information to be visible at all times without requiring mouse hover. Check out this image of the chart. This is the code snippet for my chart: < ...

How to create a manual mock for @material-ui withStyles in React using Jest

I have been experimenting with creating manual mocks for the @material-ui/core/styles module, specifically targeting the HOC known as withStyles. Initially, using an inline mock with jest.mock function worked flawlessly. However, when attempting to reloca ...

Updating to the latest version of Next.js will result in a modification of the API path

I recently updated my app to the latest version of nextjs (13.1.6) and encountered a problem where all my requests are now failing. It seems that the URL I specified in the request creator, based on the ENV value, is being overwritten. .env file CONST NEXT ...

The outcome of using jQuery animate is not what you'd expect

When hovering over a selection of icons, an animation is triggered that involves animating the left and top position of a different image. However, if the cursor is moved quickly over all the icons, the animated images do not return to their initial state ...

How can you use jQuery to add a select element dynamically and then clear the selected choice?

Trying to build a dynamic form in the Play Framework, but my javascript skills are lacking. I found this jQuery example for adding fields dynamically, but I want to add both a text field and a select box each time. My attempt involves using this answer ...

How can I ensure that a datepicker field in bootstrap-vue clears after selecting a date using vue.js?

I'm currently using bootsrap-vue and have encountered an issue with the datepicker. Once a date is selected, there seems to be no way to clear the field. <template> <div> <label for="datepicker-placeholder">Date picke ...

Guide to generating a unique identification for a file in nodejs

Seeking help to fix issues in the code below. Any suggestions? 1- The files are not being created in the designated directory records. How can I ensure they are saved in the correct folder? 2- Involving node uuid library, how can I generate unique ids fo ...

Utilize Javascript to reconfigure the JSON structure

Hey there, in my code I retrieve a JSON blob that has the following structure: [ { "ts": 1431736740, "aggs": { "DNS": { "min": 20, "max": 21, }, "SEND": { ...

Exploring deep JSON parsing with body-parser and express

I am currently working on an iOS app that sends a JSON packet to a webserver. Below is the webserver code snippet: var express = require('express'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); ...

Generate a unique ID each time the page is loaded or refreshed

I'm currently working on a function that will display a unique ID or a different video each time the page is loaded or refreshed. My main objective is to design a splash intro popup that features a <section> with a full-screen YouTube video bac ...

Tips for troubleshooting the "Vue-Formulate component resolution error"

I am relatively new to working with Vue and I'm finding it challenging. Currently, I am attempting to use Vue-Formulate to create a registration form in my Vue app using Vue 3. Following the official documentation provided by Vue-Formulate, this is ho ...

Preference for executing multiple dependent ajax calls synchronously

There are various approaches to handling multiple dependent ajax synchronous calls, but two of the most commonly used methods are the jQuery defer method and using callbacks on success. My inquiries include: 1) What are the benefits of utilizing one me ...

Updating style in Javascript can sometimes be a bit tricky

What's preventing this from working? localStorage.fontSize contains the correct value, but the initial document.body.style.fontSize = localStorage.fontSize + "pt"; doesn't update the style. <script type="text/javascript> if(!localStorage. ...