How to apply class binding within a v-for loop in Vue.js

When using Vuejs3, I am currently iterating through an array of objects:

<div 
   v-for="ligne in lignes" 
   :key="ligne.id" 
   :class="{ 'border-b-2':isSelected }" 
   :id="`ligne_${ligne.id}`"
 >
     <span @click="select(ligne.id)">X</span>
</div>

I am trying to apply the class 'border-b-2' only on the selected line, but I am facing difficulties in doing it dynamically. Setting isSelected to true in the vue devtools is applying this style to all lines instead of just the selected one.

As a temporary solution, I have wrapped this code inside a function (select(id)) and changed the html class accordingly.

document.getElementById(`ligne_${id}`).classList.add('border-b-2')

This approach seems overly verbose. Is there a way to accomplish this by utilizing the :key or the v-for loop more effectively?

Answer №1

Make sure to define the identifier as isSelected instead of using a boolean:

const app = Vue.createApp({
  data() {
    return {
      lignes: [{id: 1}, {id: 2}, {id: 3}],
      isSelected: [],
    }
  },
  methods: {
    select(id) {
      if(this.isSelected.includes(id)) {
        this.isSelected = this.isSelected.filter(s => s !== id )
      } else this.isSelected.push(id)
    }
  }
})
app.mount('#demo')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="ligne in lignes" :key="ligne.id" 
    :class="isSelected.includes(ligne.id) && 'border-b-2'"
  >
    <span @click="select(ligne.id)">X</span>
  </div>
</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

Leveraging ternary operators within HTML elements

Currently, I am utilizing the Vue.js framework to create a dynamic list that updates based on two different list objects. My main objective is to adjust the border of the list cards depending on a specific condition. Below are the defined cards: <li ...

Is it possible for AJAX to update a button's argument?

After successfully using AJAX to extract a data value from a button click, I am now looking to pass this value as an argument to another button on the same page. Is there a way to achieve this seamlessly? Sample code from test.html: <a href="#" onClic ...

Incorporate React into current Node express application by utilizing a content delivery network (CD

I'm currently in the process of developing a web application utilizing both Node and React. Instead of having separate Node and React applications, I decided to integrate React directly into my existing setup. To achieve this, I attempted importing th ...

Display the div only during the printing process

Imagine I have a situation where there is a block of content that I only want to show when printing. It looks something like this: <div id="printOnly"> <b>Title</b> <p> Printing content </p> </div&g ...

Using VueJs to invoke a plugin from a .js file

I'm seeking a deeper understanding of working with vueJS. My current setup In my Login.vue component, there is a function logUser() from UserActions.js which in turn calls the postRequest() function from AxiosFacade.js Additionally, I use a plugin ...

Ways to evaluate the amount of traffic on a webpage?

Recently, I encountered an issue while creating a page to showcase blog posts. Each post had the typical social media share buttons like "Facebook like," "tweet this post," and "+1." Additionally, there were some extra JavaScript functions added for variou ...

Strange occurrences within the realm of javascript animations

The slider works smoothly up until slide 20 and then it suddenly starts cycling through all the slides again before landing on the correct one. Any insights into why this is happening would be greatly appreciated. This issue is occurring with the wp-coda- ...

Basic PHP code converted into a JavaScript function for an onSubmit event within an HTML form

I have been trying to figure this out for hours. The goal is to submit a form only if one of the inputs matches a PHP echo. To simplify the script, it looks something like this: <head> </head> <body> <?php $A = rand(0,10); $B = r ...

Looking to retrieve the key value or iteration of a specific item within an Angular UI tree?

Here is a snippet of code showcasing how to use angular-ui-tree: <div ui-tree> <ol ui-tree-nodes="" ng-model="list"> <li ng-repeat="item in list" ui-tree-node> <div ui-tree-handle> {{item.title}} </div& ...

Vue 3 - Compelled to utilize any data type with computedRef

Recently, I've been diving into Vue/Typescript and encountered a puzzling error. The issue revolves around a class named UploadableFile: export class UploadableFile { file: File; dimensions: Ref; price: ComputedRef<number>; ... constr ...

When using JSON.stringify, the output is null. However, when using document.write, the data

I am currently working on a plugin for crawljax that involves executing some JavaScript code, similar to the following: String result = browser.executeJavaScript(script).toString(); The script code is as follows: function getElementPosition(id) { var el ...

Uncertainty surrounding the distinction between global variables (var) and block variables (let, const) in Node.js

It's common knowledge that var is a global variable in node js and can be accessed from anywhere. However, I found myself perplexed by the following examples: In the first example, accessing global_1 poses no issues as it is a global variable. var g ...

Invoke the function for every element during the mapping process

I am attempting to call a function in React Native maps for each element. This function will randomly determine properties of the rendered component, making sure that each component is unique. The renderComponent function takes an argument called item as w ...

Vue2: when passing a function as a prop, a warning will be triggered indicating that the prop has

As a newcomer to Vue, I've been enjoying working with Single File Components. Before diving into my main project idea, I decided to experiment with some small components to get a better grasp of the concept. One such experiment involved creating a co ...

Is there a shared instance for regular expressions created using expression literals?

In the book "Javascript: The Good Parts" by Crockford, there is a code snippet that highlights how RegExp objects created using regular expression literals share a single instance: function create_matcher() { return /a/gi; } var x = create_matcher(); ...

Having trouble retrieving data from getters in the Vue store while inside a template

Within my component, I have set up computed properties that are supposed to display text for blopp and blipp. However, while blopp is working fine, blipp is not showing anything. The end goal is to have blipp generate a list of strings from the store state ...

Is it feasible to access a service instance within a parameter decorator in nest.js?

I am looking to replicate the functionality of Spring framework in nest.js with a similar code snippet like this: @Controller('/test') class TestController { @Get() get(@Principal() principal: Principal) { } } After spending countless ho ...

Merging Vue.js with vue.router in history mode and Django unfortunately results in an error

When I set publicPath to '/static/' in my webpack configuration, everything works smoothly with my Vue.js app on a Django Webserver for both development and production environments. However, when attempting to implement history mode, I need to m ...

The display message in Javascript after replacing a specific string with a variable

I'm currently working on a task that involves extracting numbers from a text input, specifically the first section after splitting it. To test this functionality, I want to display the result using an alert. The text input provided is expected to be ...

Is it possible to access Firebase data in Vue.js, with or without Vuefire, using a router parameter before the DOM is rendered?

When I navigate to a view from another view, I pass the itemId as a param value to vue router. My goal is to call firebase with that itemId in order to filter the data and use the filtered result/data in the UI. Specifically, I am utilizing vuefire. The ...