[Vue.js] Access (Get/Reference) DOM Element


How to access (get/reference) DOM Element in Vue.js?

Assume we have the following audio element in HTML code:

<audio src="Wat_Metta_Buddha_Qualities.mp3"></audio>

We can give id to the audio element in HTML:

<audio id="audioElm" src="Wat_Metta_Buddha_Qualities.mp3"></audio>

And then access the audio element via getElementById in JavaScript:

var myAudio = document.getElementById("audioElm");
// do something with myAudio

But this seems not an elegant and canonical way to reference a DOM element in Vue.js. So I tried some googling [1], and found no working answer for my Vue version 2.1.10.

Then I read the documentation of Vue.js, and found the ref attribute, which is exactly what I need.

The solution [2] is to give the ref name to the audio element in HTML:

<audio ref="audioElm" src="Wat_Metta_Buddha_Qualities.mp3"></audio>

Inside the Vue instance, access the DOM element by this.$refs.audioElm (this here is the Vue instance). For example, you can play the audio in JavaScript code by:

this.$refs.audioElm.play();

Or stop playing by:

this.$refs.audioElm.pause();

The instance property $refs holds the DOM elements that have ref registered.

If you need complete examples of getting DOM elements in Vue.js, see my posts of play audio [3] and toggle audio [4].


Tested on:
  • Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
  • Vue.js 2.1.10.

References:

[1]vuejs reference element - Google search
[2]
[3][Vue.js] Play Audio Sound on Click Event of DOM Element
[4][Vue.js] Toggle (Play/Pause) Audio Sound on Click Event of DOM Element