P
P
pqgg7nwkd42020-01-21 18:33:33
Vue.js
pqgg7nwkd4, 2020-01-21 18:33:33

What is the correct way to get DOM elements in the order they are on the page when using VUE v-for?

Good afternoon.
I'll try constructively:

<Foo v-for="el of elems" :key="el" ref="el">{{ el }}</Foo>

I need to get a list of these Foo's in the order they are output.
It would seem that this.$refs.el should contain them in the order in which they were displayed, but it turned out not to be the case - the order is not guaranteed. The documentation does not say anything about this, only "When ref is used in conjunction with v-for, then ref will be an array containing the child components rendered from the data source.".
An example illustrating the problem (you need to open the console on the page, the code is in the App.vue file):
https://codesandbox.io/s/confident-http-i05jm
In the example, I display a div several times, in my project it is a component and I need access not to the element, but to the component.
Actually how to do it right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2020-01-21
@Kozack Vue.js

Use an index as a key
v-for="(el, i) in elems" :key="i"

P
pqgg7nwkd4, 2020-01-21
@pqgg7nwkd4

Temporarily did this:

let dws = [];
if (this._vnode && this._vnode.children) {
    for (let chVnode of this._vnode.children) {
        if (chVnode.componentInstance) {// В вашем случае может понадобиться более сложный фильтр
            dws.push(chVnode.componentInstance); 
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question