I have an HTML 5 video inside my page and I would like to set the src dynamically. I'm using vue, inside my js controller I set a variable with the video path then I use the variable in my page as below:
<video width="450" controls>
<source v-model="controller.var" v-bind:src="var" type="video/mp4">
</video>
The player doesn't load the video but my var is properly set with the right url. What I'm missing here?
Thanks
First, I don't know if you are actually using var
in your template, but if you are, Vue will throw a warning in the template.
- avoid using JavaScript keyword as property name: "var" in expression :src="var"
Second, you cannot dynamically change the source element.
From the HTML5 specification,
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.
So, bind your data to the src
attribute of the video
element.
<video width="450" controls :src="video"></video>
console.clear()
new Vue({
el:"#app",
data:{
video: "https://www.w3schools.com/tags/movie.mp4"
},
methods:{
changeVideo(){
this.video = "http://techslides.com/demos/sample-videos/small.mp4"
}
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<video width="450" controls :src="video"></video>
<div>
<button @click="changeVideo">Change</button>
</div>
</div>
Adding the key attribute with the source's URL to the video element will cause both video and source to be updated when the URL changes:
<video
:key="video"
width="450"
controls
>
<source
:src="video"
type="video/mp4"
>
</video>
This supports dynamic replacement of a video + source.
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