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")
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.
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.
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.
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.
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 id
s
<div id="app">
<div v-for="count in length" :id="'divNum'+count" class="target">{{count}} </div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With