Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS find element by key

Tags:

vue.js

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 :(

like image 990
Morgan Le Floc'h Avatar asked Mar 13 '18 09:03

Morgan Le Floc'h


1 Answers

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.

like image 116
Jacob Goh Avatar answered Sep 20 '22 14:09

Jacob Goh