1

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

 1 year ago
source link: https://siongui.github.io/2017/02/24/vuejs-access-dom-element/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

February 24, 2017

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:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK