在我的组件生命周期中什么时候可以开始访问 this.$refs?

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

我试图在加载以下单文件 Vue.js 组件时连接到某些 HTML5 音频事件:

<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>

当触发带有 this.$refs 的行时,引用 player 似乎尚未注册,因此会导致错误。在组件加载时附加这些事件侦听器的正确方法是什么?

您应该可以在 mounted 挂钩中访问它。我猜问题出在 v-if 这里。您是否可以将其更改为 v-show

如果您做不到,您可以尝试使用 $nextTick 方法。这也应该有效,因为元素的实际渲染直到下一个刻度才会发生。