[Vue.js] Play Audio Sound on Click Event of DOM Element


Play audio sound if uers click on DOM Element in Vue.js/JavaScript.

Demo

The key points of the following source code:
  • Use v-on directive to attach event listener of button onClick event.
  • Use ref attribute to register a reference to audio element. We will later access the audio element by the unique reference name audioElm in the event listener.
  • If users click on the button, call play() method of the audio element to play the sound.
index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue.js Play Audio Sound Onclick Demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div id="app">
  <button v-on:click="play" type="button">Click Me to Play Sound</button>
  <audio ref="audioElm" src="../../javascript/play-toggle-sound/Wat_Metta_Buddha_Qualities.mp3"></audio>
</div>

<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
'use strict';

var app = new Vue({
  el: '#app',
  methods: {
    play: function(event) {
      this.$refs.audioElm.play();
    }
  }
})

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]
[2]Event Handling — Vue.js
[3]