Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs with HTML5 audio property

I'm using Vuejs to make a control panel for audio, I want to get the currentTime property bind to a computed value, so I write

  computed: {
    'currentTime': {
      cache: false,
      get: function () {
        return document.getElementById('player').currentTime
      }
    }
  },

and here is my audio tag:

  <audio :src="musicSrc" preload="auto" id="player">
    <p>Your browser does not support the <code>audio</code> element.</p>
  </audio>

I can get it in ready:

  ready () {
    this.player = document.getElementById('player')
  },

I can control it in methods

play: function () {
  this.player.play()
},

But when I use {{ currentTime }} in template I got

Error when evaluating expression "currentTime".

Uncaught TypeError: Cannot read property 'currentTime' of null

like image 498
zl2003cn Avatar asked Mar 01 '16 01:03

zl2003cn


3 Answers

For vue 2.0 the way to reference an element has changed.

In HTML
<audio ref="audio" controls>

In Vuejs
this.currentTime = this.$refs.audio.currentTime

like image 61
Sanyam Jain Avatar answered Sep 18 '22 00:09

Sanyam Jain


You should register via v-el to reference it

<audio v-el:audio :src="musicSrc" preload="auto"></audio>

then access it in you vue instance via $els property, like so

ready: function() {
    this.$els.audio.play();
}
like image 32
Joseph Dan Avatar answered Sep 22 '22 00:09

Joseph Dan


It seems a particularly "vue" way to approach this is like so:

HTML:

<audio @timeupdate='onTimeUpdateListener'></audio>

JS:

export default {
  data () {
    return {
      currentTime: '00:00' // The initial current time
    }
  },
  methods: {
    onTimeUpdateListener: function() {
      // Update current time
      this.currentTime = this.$els.audio.currentTime
    }
  }
}

Credit for this approach goes to the author of this SO answer.

like image 30
Isaac Gregson Avatar answered Sep 18 '22 00:09

Isaac Gregson