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
For vue 2.0 the way to reference an element has changed.
In HTML<audio ref="audio" controls>
In Vuejsthis.currentTime = this.$refs.audio.currentTime
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With