How to dynamically add multiple classes in Vue.js

I want to add multiple classes when the user clicks on an item. Currently, I have this code snippet:

<div :class="[ item === form.score ? 'text-black bg-white': '' ]"
    @click="form.score = item"
    v-for="item in 10">
   {{ item }}
</div>

However, only the bg-white class is being added. Is there a more efficient solution for this?

Answer №1

There are several ways to achieve this:

:class="[ item === form.score ? 'text-black': '', item === form.score ? 'bg-white': '']"

or

:class="[ 'text-black': item === form.score, 'bg-white': item === form.score ]"

or

:class="[ 'text-black bg-white': item === form.score]"

additional information

Answer №2

Give this a shot:

:class="{ 'text-black': is_selected(item), 'bg-white': is_selected(item) }"

and in your functions:

is_selected(item) {
 return this.data.value === item
}

or an improved version would be

:class="selected_classes(item)"

and in your functions:

selected_classes(item) {
 return data.value === item ? ['text-black', 'bg-white'] : ''
}

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

The Vue design is not being reflected as expected

Encountering a peculiar issue where the style in my Vue component is not being compiled and applied alongside the template and script. Here's the code snippet: To achieve an animated slide fade effect on hidden text upon clicking a button, I've ...

reveal a segment on hover over text blocks

I am struggling with making a section visible on mouseover when it has the display:none property. I want it to become visible when I hover over certain paragraphs. Here is the CSS code snippet: .buttons { width: 97px; margin: 0; padding: 0; font ...

Are there any alternative methods to define a constructor function in TypeScript that do not involve utilizing classes? Upon researching on this subject, it appears that all sources suggest using classes

Is it possible to transform this class declaration into a constructor function without losing TypeScript compatibility? class Animal { constructor(public name: string, public energy: string) {} } ...

Utilize flexbox to achieve center left alignment of elements within a DIV container

I've encountered a puzzling issue with my inherited markup. The width is defined on the outermost div and then inherited by each child div, creating a dynamic width scenario. The challenge I face is aligning the pink wrapper div to match the exact wi ...

What is the best way to rearrange three divs into two columns?

I am trying to rearrange the order of three divs in my markup layout. The desired layout is to display div one first, followed by three underneath it in the first column. Then, in the second column, I want to only show div two. My current CSS configuratio ...

When attempting to send coordinates to the Polyline component in React Native, an error is encountered stating that NSNumber cannot be converted to

Trying to pass coordinates from BackgroundGeolocation.getLocations() is causing an issue. Upon passing the coordinates, I encounter the following error message: JSON value '-122.02235491' of type NSNumber cannot be converted to NSDictionary I ha ...

Setting values and options in Material UI AutoComplete and then assigning the selected value to an object when onChange event occurs - how can it be

I am working on a project where I have a brand object with the field cat_id. When the page loads, categories are loaded into an autocomplete select. My goal now is to set the value of category id as the value for a category option in the autocomplete, an ...

Is there a way to separate a string using two different delimiters?

Here is my code snippet : <template> ... <p v-for="club in clubs">{{club}}</p> ... </template> <script> export default { data: () => ({ clubs: '' }), mounted () { let dataClub = "- ...

Getting query parameter with hyphen in nextJS 13 - step by step tutorial

One of the challenges I am facing involves accessing a query parameter with a hyphen in its name within a route: /?previous-page=building-details Within my Page component: import EnergyEfficiency from "@/ui/energy-check/energy-efficiency" cons ...

Numerous Axios GET calls made by various components

I am facing an issue where I have two different components rendering on the main screen. Both of them make multiple axios.get requests to fetch data. However, upon initial page load, only the last component successfully retrieves the data while the first c ...

Please input JavaScript into Chrome

Can anyone explain why my code only works correctly the second time it's run? ThisElement = document.querySelector("#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text"); ThisElement.innerText = ...

Tips for ensuring only digits can be entered in a textbox on Firefox

Having trouble validating digits in a textbox on both IE 9 and Firefox versions 4 & 5. Does anyone know how to solve this issue? I've attempted the solutions provided in previous questions, but I'm still encountering problems. My goal is to only ...

Show the input from one HTML form on a different HTML form

Seeking guidance on utilizing local storage in HTML5. How can I extract information from one form and present it on another HTML form page? Picture this: two forms at play here. Upon populating form 1 and hitting the submit button, the content should be v ...

Making adjustments to a JSON object before saving it to a file with Postman and Express

I have successfully created a POSTMAN call to a server that provides a JSON response containing a list of items as shown below:- { "count": 6909, "setIds": [ "1/7842/0889#001", "2/4259/0166#001", "ENT0730/0009", "9D ...

Ensuring the length of a Multidimensional Array

Today I decided to delve into coding with Google Sheets and JavaScript. As I was working on a project, I encountered a small issue: function myFunction() { var sheet = SpreadsheetApp.getActiveSheet(); var data = sheet.getDataRange().getValues(); fo ...

Modify the NAME attribute when clicked using Jquery

I am attempting to modify the NAME attribute of a DIV with the text from a textbox using jQuery. Take a look at my code snippet: http://jsfiddle.net/e6kCH/ Can anyone help me troubleshoot this issue? ...

I'm experiencing issues with the autofocus attribute when using the bmd-label-floating feature in Bootstrap Material Design version 4.1.1

Issue with Bootstrap-JavaScript Autofocus Attribute Upon page load, the autofocus attribute fails to trigger the addition of the is-focused class by the Bootstrap-JavaScript for the corresponding (bmd-)form-group. https://i.sstatic.net/2V374.png <fie ...

What is the method for reviewing the logs in Phpmyadmin?

Can logs (error logs, process logs) be checked in Phpmyadmin without using the console history option? Is it possible to view recent changes made to tables or databases in Phpmyadmin and identify who made those changes? ...

Properly Accessing Values within Nested Arrays Using ForEach Loop in JavaScript

Question: b = [1, 2, 3, [4, 5], 6]; b.forEach((value, index) => { if (Array.isArray(value)) { value.forEach(element => element += 2) } else { value += 2; } console.log(`The value at ${index} is ${value}`); }) ...

Exploring the power of regular expressions in Javascript when used between

Consider the scenario outlined in the text below I desire [this]. I also desire [this]. I do not desire \[this] I am interested in extracting the content enclosed within [], but not including \[]. How should I approach this? Currently, I have ...