Search code examples
javascriptvue.jsv-for

Nested V-For active Class


I'm trying to bind an active class @click to a nested item in array of objects.

i have the following array:

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 I Loop through this array 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>

I want to set an active class on the clicked element on the nested v-for. I've tried it like that.

But this gives every first element in the array that class.

How can I fix that?


Solution

  • You can keep the id of the last clicked element and bind a class depending on that id.

    Also the format of the arr was wrong.

    Conditional class binding

    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>