Utilize the v-if directive within a v-for loop

I am currently iterating over an array named cars using the v-for directive. I would like to implement a condition within this loop so that if the color property matches a certain value, a specific CSS style is applied.

 <p v-for="car in cars" :key="car.color">

The desired code should look something like this:

If car.color == "red", apply class="style1"; else if car.color == "green", apply class="style2"... and so forth.

Answer №1

What you are referring to is the concept of dynamic class bindings.

v-if is used for conditional rendering, determining whether an element should be displayed on the screen or not.

By utilizing class bindings, you can assign a class, such as "style1" or "style2", to an element based on certain conditions:

<p v-for="car in cars" :key="car.id" 
    :class="{ 
      style1: car.color === 'red',
      style2: car.color === 'blue'
    }">
    {{ car.name}}
  </p>

You can also use a function like

:class="someFunction(car.color)"
(as mentioned by Jaromanda X in a comment).

Vue Playground example

Although using v-if with v-for may not directly relate to your current issue, it's good to know that you can use both simultaneously, just not on the same element. The Vue documentation provides a solution:

Avoid using v-if and v-for together on the same element to prevent implicit precedence issues

To address this, move v-for to a parent tag for clearer visibility

<template v-for="todo in todos">
  <li v-if="!todo.isComplete">
    {{ todo.name }}
  </li>
</template>

Answer №2

Implementing Dynamic Class Binding

<p v-for="car in cars" :key="car.color" :class="getCarStyle(car.color)">
  {{ car.name }}
</p>

Defining the getCarStyle Method

getCarStyle(color) {
   if (color === "red") {
     return "style1";
   } else if (color === "green") {
     return "style2";
   }
}

Answer №3

<div id="unique-content">
  <script setup>
    import { ref } from 'vue';

    const message = ref('Hey there!');

    const vehicles = {
      vehicleOne: {
        brand: 'Ford',
        type: 'SUV',
      },
      vehicleTwo: {
        brand: 'Chevrolet',
        type: 'Truck',
      },
    }
  </script>

  <template>
    <h1>{{ message }}</h1>
    <input v-model="message">

    <p v-for="vehicle in vehicles" :key="vehicle.type" :class="vehicle.type"> {{ vehicle.brand }}</p>
  </template>

  <style scoped>
    .SUV {
      color: blue;
    }

    .Truck {
      color: red;
    }
  </style>
</div>

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

Building a flexible table in React JS based on specific keys: a complete guide

I'm currently working on developing a dynamic table component using React JS. The component at the moment has a fixed header with the most common result keys. Some results contain additional information such as phone numbers and degrees. I'm loo ...

JavaScript plugin designed for effortless conversion of JSON data to structured HTML code

I want to add this JSON data to an HTML element. [ { "website":"google", "link":"http://google.com" }, { "website":"facebook", "link":"http://fb.com" } ] Is there an easy way to convert this using a plugin ...

Having issues with connecting the front-end (Vue) to the API (Node.js), utilizing nginx on an EC2 AWS instance running Ubuntu 20.04

I am currently in the process of setting up web servers. Initially, I decided to use NodeJS with Express for backend, specifically listening on port 3002. app.js is now successfully listening at port 3002 Subsequently, I configured the Ubuntu firewall to ...

Creating interactive tables in JavaScript with dynamic row adding, editing and deleting capabilities

Whenever I try to add a new row by clicking the Add Row button, an error occurs. My goal is to append a new 'tr' every time I click the add row button. Each 'td' should include a checkbox, first name, last name, email, mobile number, ed ...

Vue cookies experiencing issues with updating cookie values correctly

My goal is to store user preferences (maximum 2-3 users) in a cookie for easy access. Upon login, I first check if the 'users' cookie exists. If not, I create it. If it does exist, I check if the current user is included in the cookie. If not, I ...

extracting ng-repeat values and passing them to the controller

I have created a form that dynamically increases whenever the user clicks on the add sale button Here is the HTML code: <fieldset data-ng-repeat="choice in choices"> <div class="form-group"> <label for="name"> Qu ...

Creating two separate divs that can scroll independently while also limiting each other's scroll depth can be achieved by utilizing

I am attempting to replicate the unique scrolling feature seen on this particular page. Essentially, there are two columns above the fold that can be scrolled independently, but I want their scroll depths to be linked. When a certain depth is reached whil ...

Creating a form with required fields in Angular and using the ngIf directive

Update: modified the sample code to incorporate TypeScript for better clarity I have a form with various buttons for users to choose from. The submit button is initially disabled until a user selects a button. However, there's a unique requirement wh ...

Having issues with importing images in Next.js using the Next Images package

Having trouble with importing images locally from the images folder. Error message: "Module not found: Can't resolve '../images/banner1.jpg'" https://i.stack.imgur.com/Dv90J.png Attempting to access images in ImagesSlider.js file at compo ...

This function is functional with jquery version 1.4.2 but encounters issues with jquery version 1.9.1

I have encountered an issue with a script that submits data to my database. The script worked perfectly on version 1.4.2, but the template I am using now requires version 1.9.1, so I updated my site accordingly. However, after the update, I am facing an er ...

Ignoring page redirects in Node.JS

Directories are organized as follows: -public -landing -landing.html -Login -login.html -register -register.html -routes HTMLroutes APIroutes - server.js All commented code are attempts I have made without success if (bcry ...

express middleware is not compatible with prototype functions

I've encountered a perplexing issue while working with the node.js express framework. Let's say I have a file called test.js containing the following code: function a(){ } a.prototype.b = function(){ this.c("asdsad"); } a.prototype.c = f ...

Eliminating attributes in mapStateToProps

When wrapping material TextField with a redux component, it is important to consider that some properties should be used in mapStateToProps only and not passed directly to the component. Otherwise, an Unknown prop warning may occur. Even specifying an unde ...

Something went wrong with @wdio/runner: unable to establish session

After successfully developing cucumber tests that passed and tested some URLs with Chrome, I encountered errors when uploading to the pipeline despite the tests succeeding. Webdriver generated the following errors: INFO webdriver: DATA { 57[0-0] capabili ...

Tips for showcasing a restricted amount of data with Angular.js

I've been exploring different ways to limit the results using limitTo, but unfortunately, I'm encountering unexpected issues. Currently, the entire list is being displayed when I only want to show 8 key-value items in a 4/4 block format. You can ...

What makes realtime web programming so fascinating?

Working as a web developer, I have successfully created various real-time collaborative services such as a chat platform by utilizing third-party tools like Redis and Pusher. These services offer straightforward APIs that enable me to establish bidirection ...

When I hover over div 1, I am attempting to conceal it and reveal div 2 in its place

I need help with a CSS issue involving hiding one div on mouse hover and showing another instead. I attempted to achieve this using pure CSS, but both divs end up hidden. Would jQuery be necessary for this task? Below is the CSS/HTML code I wrote: .r ...

Unable to set initial values for Select Option in Redux-Form

I have implemented an update form using redux-form, where the form value is initialized using initialValues. For example: <DataEdit initialValues={ Data }/> The form in the DataEdit page looks like this: <Field name="Data.taxTitle" comp ...

Discovering all class names following the same naming convention and storing them in an array through Javascript

Hey everyone, I could use some assistance with a coding challenge. I'm aiming to extract all class names from the DOM that share a common naming convention and store them in an array. For instance: <div class="userName_342">John</div> & ...

What is the best way to create a self-referencing <div> in HTML?

After extensive research, I turn to seeking advice and guidance on Stack Exchange. I have a seemingly straightforward goal in mind. I want to create a <div> id/class that will automatically generate a link to itself using scripting of some sort. Be ...