Reputation: 324
I've just wanted to know if it is possible to find a DOM element by the key attribute of vue? I'm currently working with a list. I'm displaying it via v-for directive on a div. I'm binding the key with the index of the elements.
v-for="(apk, index) in project.apks" v-bind:key="index"
It would really help me if i could compute something for each of these elements as soon as they are fetch from my server and displayed. It's just parsing a file and looking for keyword, and accordingly choosing a css class for the items.
The problem is I dont know how to call a method for each of these elements as soon as they are added to the DOM. They are a lot of html events but i couldnt find one representing the object beeing inserted to dom :(
Upvotes: 15
Views: 31165
Reputation: 1125
For Vue 3.2.47+ searchers, you can access elements of a v-for
array with a ref
to an array directly: (docs).
const itemRefs = ref([]);
<Comp v-for="item in list" ref="itemRefs">
{{ item }}
{{ itemRefs[2] }}
</Comp>
However, if your v-for is a list of custom components, be sure to expose any fields or functions you need with defineExpose. (example).
If furthermore you require that the list of refs maintain the same order, I found this answer to be very helpful.
Upvotes: 0
Reputation: 379
The problem is I dont know how to call a method for each of these elements as soon as they are added to the DOM. They are a lot of html events but i couldnt find one representing the object beeing inserted to dom :(
You can create a new component with your v-for
and just call the created() hook.
/* On your main function */
<div v-for="apk in project.apks">
<apk :data="apk"></apk>
</div>
/* On your 'apk' component */
export default {
props: [ "data" ],
created() {
console.log("Created !");
}
}
Upvotes: 1
Reputation: 20855
The purpose of key
is not selecting element. Even if it can be done, don't do it.
The proper way to do it is by using ref.
for example, add ref
attribute to your html like this
v-for="(apk, index) in project.apks" v-bind:key="index" :ref="'sample-ref-'+index"
and then in your methods, you can get the DOM using this.$refs['sample-ref-0']
,this.$refs['sample-ref-1']
and so on.
Hope this helps.
Upvotes: 28
Reputation: 121
I found that if you give the 'ref' the same name in a v-for, like this:
<div v-for="data in list" :key="data.id" ref="bar"></div>
Then you will find they just store in an array called 'bar' and you can visit them by:
this.$refs['bar'][index]
Upvotes: 10
Reputation: 6934
something like this could allow you to find a component by key :
this.$children.forEach(child=>{
print("child.$vnode.key")
})
also use mounted , as it gets called when the component is added to the dom:
mounted:function(){
this.$el.querySelector("#ele1")...
}
Upvotes: 4