Search code examples
javascripthtmlvue.jshtml5-audio

When during my component lifecycle can I start accessing this.$refs?


I'm trying to hook in to some HTML5 audio events when loading the following single-file Vue.js component:

<template>
    <audio ref="player" v-bind:src="activeStationUrl" v-if="activeStationUrl" controls autoplay></audio>
</template>

<script>
export default {
    props: ['activeStationUrl'],
    data () {
        return {
            // Last media event that was recorded. We don't hook in to all events. More info at
            // https://developer.mozilla.org/en-US/docs/Web/Apps/Fundamentals/Audio_and_video_delivery/Cross-browser_audio_basics.
            'lastEvent': null,
        }
    },
    mounted () {
        const eventsToHookInTo = ['loadstart', 'canplay']
        for (var eventToHookInTo in eventsToHookInTo) {
            this.$refs.player.addEventListener(eventToHookInTo, function () {
                this.lastEvent = eventToHookInTo
            })
        }
    },
}
</script>

When the line with this.$refs triggers, the reference player doesn't seem to be registered yet, so this causes an error. What is the correct way to attach these event listeners when the component loads?


Solution

  • You should be able to access it in the mounted hook. I am guessing the problem is in the v-if here. Is there a possibility you can change this to a v-show?

    If you can not do that you could try using a $nextTick method. This should work as well since the actual render of the element does not happen until the next tick.