[Vuejs]-Ref only gets the last element – VueJS

1πŸ‘

If you want to set those tags a same ref name, you should place them into a v-for in order to make Vue store them in form of array.

In addition, if you want to distinguish them in that array. You can use :ref="" instead of ref="" for e.g. <div :ref="'newsanimate'+i" v-for="i in [1, 2, 3]" :key="i"></div>

So as a result, if you really want to get what you want. Just add v-for="i in [0]" :key="i" to the parent <div>. For e.g.

<template>
    <section id="news">
        <div id="newscontainer" v-for="i in [0]" :key="i">
            <div class="latestevent pt-4">
                <h1 class="latestnews">LATEST NEWS AND EVENTS</h1>
                <span class="float-right readall">Read all news</span>
            </div>
            <div>
                <div class="ako animated" ref="newsanimate" :style="'background-image: url('+getimgurl('bell.jpg')+')'">
                    <div class="akodesc">
                        <p><a href="#">BELL Blue Day</a></p>
                    </div>
                </div>
            </div>
            <div>
                <div class="ako animated" ref="newsanimate" :style="'background-image: url('+getimgurl('family.jpg')+')'">
                    <div class="akodesc">
                        <p><a href="#">Family Day</a></p>
                    </div>
                </div>
            </div>
            <div>
                <div class="ako animated lastako" ref="newsanimate" :style="'background-image: url('+getimgurl('flores.jpg')+')'">
                    <div class="akodesc">
                        <p><a href="#">Q Flores de Mayo</a></p>
                    </div>
                </div>
            </div>
        </div>
    </section>
</template>

0πŸ‘

You are overwriting previous refs if you use it that way. If you want your newsanimate ref to be an array then use a v-for with ref="newsanimate" like in this example:

<div v-for="i in 3" :class="`test${i}`" ref="newsanimate">{{i}}</div>

And here’s a fiddle: http://jsfiddle.net/eywraw8t/342633/

0πŸ‘

According to Vue.js documentation:

When used on elements/components with v-for, the registered reference will be an Array containing DOM nodes or component instances.

so, in your case, since you are not defining divs using v-for, all the previous references are overwritten by the next ones.

See here for further references.

-1πŸ‘

Maybe irrelevant. But it is quite important that you need set the :key=”” to get the correct ref.

<template v-for="(item, index) in items">
  <Item :key="index" ... ref>
     <button ref... >

Leave a comment