Towkir
Towkir

Reputation: 4014

Access loop index in the current elements data attribute - VueJS

I wanted to access the current index of a loop inside another attribute of the same element that has the v-for directive.

The HTML content is :

<div id="app">
    <div v-for="count in length" data-my-attribute="here" class="target">{{count}}</div>
</div>

And the JS code:

var app = new Vue({
    el : '#app',
    data: {
        length: 9,
    }
});

I know I can access the current loop index 'inside' the div with the class target. The way it does with the {{ count }}

But is it possible to access the count inside the value of the attribute data-my-attribute ?

(I mean in the place of the word "here")

Upvotes: 5

Views: 1692

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You could access that variable using the binding as follow :

<div id="app">
  <div v-for="count in length" :data-my-attribute="count" class="target">{{count}} </div>
</div>

like the case when you want to define a dynamic ids

<div id="app">
  <div v-for="count in length" :id="'divNum'+count" class="target">{{count}} </div>
</div>

Upvotes: 5

Related Questions