How can you selectively add a CSS class during the iteration of a VueJs object?

Using Vuetify components:

<v-layout row wrap> 
     <v-flex xs2 v-for="(month, key) in months" :key ="key">
          <router-link class = "decoration" :to="month.target">{{(month.month)}}</router-link>
     </v-flex> 

The "v-for" loop is going through an array of objects with different properties:

data () {
    return {

        months: [
           {
               month: 'Gen',
               target: ''
           },
           {
               month: 'Feb',
               target: ''
           },
          and so forth.

Is there a way to selectively add the class underlined to certain months in the first code block, rather than all of them?

Appreciate any help on this matter!

Answer №1

To apply conditional classes in Vue, simply use :class='[{"className": X}]'. Make sure to include the : before the class attribute.

Here, X represents a computed or data property in the Vue component that evaluates to a boolean value. If X is true, the specified class will be added, if false, the class will not be applied.
The className parameter refers to the name of the CSS class you want to apply.

Answer №2

Although the previous responses are accurate, it seems you are looking for a way to include both a fixed class and a dynamic class.

To achieve this, you can use the following code:

<router-link class="decoration" :class="{ underlined: CONDITION }" :to="month.target">{{(month.month)}}</router-link>

You can easily define the condition in a method like this:

methods: {
   isUnderlined() { return SOME IF STATEMENT OR SOMETHING }
}

It is important not to enclose the :class attribute in brackets [] as suggested in another response, as it should be an object {}.

Answer №3

Here's a way you can accomplish this:

<td :class="items.properties[3] == 'pawned' ? 'text-red' : ''">{{ items.properties[2] }}</td>

Answer №4

Try something along these lines:

<router-link :class="{'highlighted': month.shouldHighlight}" :to="month.target">{{(month.name)}}</router-link>

Let me know if this solution works for you!

For more information on this topic (including using multiple classes), check out: 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

Sending various values from ASP.NET to a javascript function

I am currently attempting to pass multiple parameters (eventually 4 total) into a JavaScript function from my ASP.NET code behind. In the ASCX file, I have defined the function as follows: function ToggleReportOptions(filenameText, buttonText) { /*stuff ...

Is it possible for JavaScript/React to observe the movement of elements on the webpage?

I'm searching for a solution to detect if an element moves on the screen. Currently, I have an absolute positioned div (acting as a download overlay) that appears when a document is clicked on my website. However, I want it to disappear whenever the d ...

Instead of scrolling through the entire window, focus on scrolling within a specific HTML element

I currently have the following elements: #elementA { position: absolute; width: 200%; height: 100%; background: linear-gradient(to right, rgba(100,0,0,0.3), rgba(0,0,250,0.3)); z-index: 250; } #containerofA { position: fixed; ...

Using jQuery to Construct an Object from a JSON Response

After receiving a JSON response from a PHP file via an AJAX call, I successfully retrieved the data. console.log(data["json"]); [{"value":"23","label":"Assorted Juices"},{"value":"24","label":"Water"},{"value":"25","label":"Beers"},{"value":"26","label": ...

Mesh with custom lighting effects in Three.js using specific light sources

In my current scene, I have various objects, including spheres that I want to be illuminated by pink and blue lights. However, there is also a tube geometry that should only be affected by a white light, without picking up the pink and blue colors. To ill ...

How can we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

Issue with JQuery .fadeToggle() function: Unexpected behavior causing automatic fade-out

$(document).on('click', '.tree label', function(e) { $(this).next('ul').fadeToggle(); e.stopPropagation(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul cl ...

Encountering the React.Children.only error while trying to use the <Link> component in Next.js

I'm encountering an issue with the code below: Error: React.Children.only expected to receive a single React element child. While trying to troubleshoot, I noticed that it only allows me to have one header under the link. <div className="co ...

Unexpected response: The JQuery AJAX request did not return the expected JSON data

Within my code snippet below, I have successfully obtained an object that, when printed to the console, begins with: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ,  …} However, up ...

I need assistance with displaying this array either using CSS styling or in table format. Can someone please

Seeking assistance to display this data in table format using tables, css, or bootstrap. Can anyone help? Utilized PHP Code: $url = "http://some-website.com/api/message"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $content = cur ...

Include a new key and its corresponding value to an already existing key within FormData

I have a form that includes fields for title, name, and description. My goal is to submit the form values using an API. To achieve this, I am utilizing jQuery to add key-value pairs to the FormData variable: formdata.append('description_text', jq ...

Having trouble retrieving information from the server using ajax, javascript, jquery, and php

I am currently facing an issue with sending data retrieved from a jQuery call and attempting to save it to a server file using PHP. function getSVG(){ svghead = svghead + $('#test').html(); $.ajax({ type:"POST", da ...

Attempting to develop a Discord bot equipped with commands that are restricted by permissions. Upon testing the functionality, I encountered an unexpected error

if(command.permissions.length){ let invalidPerms = [] for(const perm of command.permissions){ if(!validPermissions.includes(perm)){ return console.log(`Invalid Permissions ${perm}`); } if(!message.member.hasPermission(perm ...

Is the IE7 Modal Dialog Misaligned?

Update After some investigation, I discovered the root cause of the problem. In my code, I was referencing the height of the overlay, which resulted in different values in IE7 compared to other browsers. To resolve this issue, I adjusted the code to refe ...

Trigger event once the component has finished construction

I have integrated jqTree into my project following these steps: Adding 'p' elements with the '.root' class dynamically to the page. Calling jqTree for each of the 'p.root' elements when a button is clicked. Adding an id afte ...

I have successfully implemented ngCordova local notifications, but now I am looking for a way to make it trigger for each individual

Is there a way to trigger a notification on every logged-in user's mobile device when a value is changed and saved in Firebase? Currently, I am able to send a local notification using ngCordova when a user enters text in an ionicPopup with textarea. H ...

Connecting ViewChild to several elements

I have implemented a feature where I am displaying tabular data in DataTable for Angular. Within this, there is a button that triggers a click event. Upon clicking the button, a slide menu is displayed, which then triggers a modal open. To achieve this fun ...

How to change the state using an object as an argument in the useState hook within a function

This code uses a function component: export default function Account() { We define a constant with inputs as objects: const [state, setState] = useState({ profile: true, orders: false, returns: false, coupon: false, referrals: false, rewards: ...

The v-show directive only starts hiding elements after Vue is mounted

After creating my app with createApp and mounting it to a <div> just below the <body> tag, I realized that I need to mount it just before the closing </body> tag because the <div> must exist before I can mount my app to it. One imp ...