0

I am trying to get an array of DOM-Elements in Vue.js. If I had the following HTML structure:

 <select onchange="toggleDisability(this);" class="mySelect" id="mySelect1"> 
 </select>
 <select onchange="toggleDisability(this);" class="mySelect" id="mySelect2">
 </select>

I could get all elements with the mySelect class with normal JS like:

var arraySelects = document.getElementsByClassName('mySelect');

Now I am trying to get the same thing with Vue $refs, but I am always getting the last element. it looks like:

<select id="selection-x" ref="Axis"  @change="log($event)"></select>
<select id="selection-y" ref="Axis"  @change="log($event)"></select>

and

        log(selectElement){
   var arraySelects = this.$refs['Axis'];
}

Of course there are also options ,so that @change event gets emitted, but it doesn't do what I want it to. I want to get an array of the elements with the same ref just like it works in the example above for normal JS, where you are getting an array of select elements whose class attribute equals to mySelect.

P.S. I know ref should be unique, but how could it be then used for this particular usecase?

5
  • "... it doesn't do what I want it to." What do you want it to do? Commented Jun 25, 2018 at 10:39
  • Check my edited version please Commented Jun 25, 2018 at 10:46
  • it's no way, but you can custom a directive like npmjs.com/package/vue-multi-ref Commented Jun 25, 2018 at 10:50
  • 1
    best practice is to specify a ref for the parent element. this.$refs.selectwrap.children Commented Jun 25, 2018 at 10:53
  • Thank you Joaner your second answer is exactly what I need Commented Jun 25, 2018 at 13:34

2 Answers 2

3

No. It is not possible with ref and $refs. If you wish to do DOM manipulation then, use vue-directive or directly access DOM from the root element of the component like:

Vue.extend({
    mounted() {
        // Do what you want with your children.
        const children = this.$el.querySelectorAll('.mySelect');
    }
})
Sign up to request clarification or add additional context in comments.

Comments

0

For me the best way to do this was to set a ref on the parent element (thanks joaner in original comment), but then I also needed to run my code in the "updated" hook so my data was loaded before trying to access the dom (I also have a v-if on the same element I want to reference children):

template:

<ul v-if="dataLoaded" ref="eventlist">
    <li class="eventItem"></li>
    <li class="eventItem"></li>
    <li class="eventItem"></li>
</ul>

javascript:

updated() {
  let eventItems = this.$refs.eventlist.children
  console.log(eventItems)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.