When you look at the initial code snippet, it's clear that <video>.currentSrc
is not set when you try to log it because the video loads asynchronously. In contrast, the second snippet simply logs the <video>
element itself, and the browser console automatically updates on change, resulting in seeing currentSrc
populated.
Prior to accessing any data properties, such as currentSrc
, the <video>
element must first load the video metadata from its source. This process triggers a loadedmetadata
event. To listen for this event in your mounted
hook:
export default {
mounted: function() {
this.$nextTick(() => {
const video = document.getElementById('video')
video.addEventListener("loadedmetadata", function() {
console.log('currentSrc', video.currentSrc);
});
});
}
}
In case your site possibly has more than one <video>
element with an id
of "video"
(e.g., multiple Vue components on the page containing this <video>
), it would be more appropriate to obtain a reference to the intended element using a template ref:
<template>
<video ref="myVideo"></video>
</template>
<script>
export default {
mounted: function() {
this.$nextTick(() => {
this.$refs.myVideo.addEventListener("loadedmetadata", () => {
console.log('currentSrc', this.$refs.myVideo.currentSrc);
});
});
}
}
</script>
Check out demo 1
If your goal is solely to add an event listener, you can use the v-on
directive in the template (e.g., v-on:loadedmetadata="METHOD"
or @loadedmetadata="METHOD"
shorthand):
<template>
<video ref="myVideo" @loadedmetadata="logCurrentSrc"></video>
</template>
<script>
export default {
methods: {
logCurrentSrc() {
console.log('currentSrc', this.$refs.myVideo.currentSrc);
}
}
}
</script>
Explore demo 2