Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access loop index in the current elements data attribute - VueJS

Tags:

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")

like image 388
Towkir Avatar asked Oct 10 '18 20:10

Towkir


People also ask

How do you use a loop in Vue component?

Add key to Vue v-for loops. A common Vue best practice is to use :key in your v-for loops. key is a special attribute that lets us give hints for Vue's rendering system to identify specific virtual nodes. If we don't provide a unique key , Vue will try to minimize element movement when updating the DOM.

What is V-for in Vue?

v-for directive is a Vue. js directive used to loop over a data usually an array or object. First, we will create a div element with id as app and let's apply the v-for directive to an element with data. Now we will create this data by initializing a Vue instance with the data attribute containing the value.

How can I get data value in Vuejs?

we will write button click event and get custom attribute value in vue. js. In this example we will take on button with custom attribute like “data-id” and on click event of button we will get that value of custom data attribute value in console. we will get data attribute value using event.

What is key in V-for?

The purpose of this key attribute is to give "a hint for Vue's virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list" (from Vue. js Docs). Essentially, it helps Vue identify what's changed and what hasn't.


1 Answers

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>
like image 80
Boussadjra Brahim Avatar answered Sep 23 '22 17:09

Boussadjra Brahim