"Implementing a Nested V-For Loop with Dynamic Styling

Need help binding an active class @click to a nested item in array of objects.

The array looks like this:

var arr =
[
  {
    "id": 10,
    "name": "Main Name 1"
    "parents": {
      "id": 1,
      "name": "Name1"
    }
  },
  {
    "id": 11,
    "name": "Main Name 2"
    "parents": [
      {
        "id": 2,
        "name": "Name2"
      },
      {
        "id": 3,
        "name": "Name3"
      }
    ]
  }
]

In Vue.js, looping through the array is done like this:

<v-col cols="2" v-for="main in arr" :key="main.id">
  <b>Table {{main.name}}</b>
  <v-card
  class="ma-2 pb-6"
  v-for="parent in main.parents" :key="parent.id"
  @click="doSomeStuff"
  >
    <v-card-title>{{parent.name}}</v-card-title>
  </v-card>
</v-col>

Want to apply an active class on the clicked element within the nested v-for loop. Tried it here.

But currently, every first element in the array receives that class.

How can this be adjusted?

Answer №1

You have the option to store the id of the last clicked element and apply a specific class based on that id.

Additionally, there was an issue with the format of the arr.

Learn more about conditional class binding here

Vue.config.productionTip = false
Vue.config.devtools = false


new Vue({
  el: '#app',
  data: {
    activeId: -1,
    arr: [{
        id: 10,
        name: "Main Name 1",
        parents: [{
          id: 1,
          name: "Name1"
        }]
      },
      {
        id: 11,
        name: "Main Name 2",
        parents: [{
            id: 2,
            name: "Name2"
          },
          {
            id: 3,
            name: "Name3"
          }
        ]
      }
    ]
  },
  methods: {
    setActive(id) {
       this.activeId = id;
    }
  }
});
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div cols="2" v-for="main in arr" :key="main.id">
    <h2>Table {{main.name}}</h2>
    <div class="ma-2 pb-6" v-for="parent in main.parents" :key="parent.id" @click="setActive(parent.id)" :class="{ 'active' : activeId === parent.id}">
      <h3>{{parent.name}}</h3>
    </div>
  </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

What is the best way to incorporate an ASYNC function within a .map function to dynamically populate a table in a REACT application?

I am attempting to use the .map() method in REACT to call an async function and populate table data cells. The async function communicates with the backend of my application using data from the array being looped through. When called correctly, the functi ...

How can I transfer a value from one form to another using AngularJS?

Trying to retrieve the Id from a table and pass it to a controller, however, I am facing an issue where the Id value is lost every time the form changes. Is there a better way to handle this? Below is the service and controller code: //Retrieving IdValue ...

event handler in JavaScript that triggers upon a click

Encountering an issue with my code <tr> <td id="<?php echo; $id ?>" onclick="addrow(?php echo $id; ?>)">...</td> </tr> <tr id="<?php echo $id; ?>" class="ndisplay">...</tr> <tr id="<?php echo $i ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

Tips for organizing date columns in Bootstrap-Vue when utilizing a formatter for presentation purposes

I am working with a table containing date objects, and I have transformed them for display using the following code: { key: "date", formatter: (value, key, item) => { return moment(value).format("L"); }, sortable: true } However, this ...

What is the reason that the 400 status code consistently causes the enter catch block to execute when using axios?

In the frontend of my website, there is a contact form with three fields -> name, email, message. These fields are then sent to the backend using Axios. If a user fails to fill out any of the required fields, they should see a message saying "please f ...

Predicting the width of an HTML element to smoothly transition its opacity and width using CSS - a helpful guide

Currently, I am facing a situation where I have a span node with an innerText that I will be changing at runtime. As I change the innerText, the offsetWidth of the node will also change based on the length of the future innerText. In order to handle CSS tr ...

Inject a value sent from response.render directly into the script tag

Below you will find a pug snippet. I am looking for a way to dynamically insert the user value into the chatConfig object. script. var chatConfig = { user : 'foo', pass : 'bar', } When rendering from my Express applicatio ...

Incorporating PHP generated content into Dart without using Ajax

My current website is built using PHP (Laravel) on the server side and Javascript on the client side. Now, I am interested in replacing the Javascript with Dart. Currently, I inject data into the Javascript on the webpage like this: <script> va ...

Having trouble with Autocomplete not entering cities into the form?

While experimenting with Google's API, I have encountered confusion regarding why cities like Staten Island, Brooklyn, Queens, and various others are not being placed into the form like other cities. According to Google's API, "locality" is suppo ...

How to remove an item from the shopping cart and use a discount code with JavaScript

I need help with removing an item from the cart without deleting the entire cart, and also adjusting the price if the customer has a coupon or exceeds a certain quantity. I am working on this using JavaScript before implementing it in Django. Here is the H ...

The "Selected" option does not function properly within Angular's reactive form implementation

I am facing an issue with my dropdown menu where I want the first option to be selected by default, but it is not working as expected. I suspect that the problem lies in how I initialized the control with a default undefined value in the .ts file. Even whe ...

Combine the given name with the initial of their surname

Recently, I've been working with the Chakra UI Avatar component and ran into an issue. When attempting to display both first and last name initials, only the first name initial is showing. This problem arises when trying use user data retrieved from a ...

Dimensions of Collada Element

This is my first time delving into the world of javascript, WebGL, and Three.js. I successfully added a dae 3D model to my scene, but now I need to determine its size in order to generate objects within it. However, upon adding the dae object, it appeared ...

Update the ajax request from jquery to axios and configure the xhrFields

Can someone help me convert my jQuery request to axios? $.ajax({ type: "GET", url: "http://6232423.212342343.100.89:9000/api/v2/content/categories/", xhrFields: { withCredentials: true }, }); I attempted to do it like this: axios ...

When an Ajax call is made, my .html page transforms into a .php page using jQuery

The Issue While using my PHP function to send emails, everything goes smoothly. However, I'm facing an issue where I don't want the page to refresh, so I've implemented AJAX in the code below: reservation.html <form class="form-horizon ...

jsTableSorter plugin does not implement styling

I'm having an issue with the application of the jsTableSorter plug-in using the Blue theme. The code I'm using doesn't seem to be applying the style correctly. Can someone help me troubleshoot this problem? <!DOCTYPE HTML PUBLIC "-//W3C/ ...

`A dilemma with dynamic tooltip functionality in JavaScript`

I am currently utilizing the Tooltipster jquery plugin, which I find to be quite useful. However, I am facing a challenge in making my tooltips dynamic. Despite thinking it should be a simple task, I seem to be struggling with it. It could be due to fatig ...

utilizing a fresh item as an argument in javascript

I'm encountering an issue with a simple one-line function. The function takes an argument as an object and assigns a value to that object, but when I try to alert the value, it shows up as undefined. Can anyone help me identify what's causing thi ...

Prevent users from clicking on an element during a Vue transition using Vue's <transition> feature

Currently, I'm developing a project using Vue.js and implementing a feature where clicking on an element triggers a fade-out effect through the Vue transition tag. However, I've encountered an issue where during the fading process, the element re ...