videoloadundefinednuxt.jsrefs

change src of video tag dynamicly in nuxt js


i'm using nuxt.js . i have a tag and i want to change the src dynamically but i cannot call load() method to refresh the video and start playing .

tag :

<video ref="videoPlayer">

"change video" function in nuxt methods :

 this.videoUrl = "new url";
 let videoPlayer = this.$refs['videoPlayer'];
 videoPlayer.load();

load() not working ! it has error . i cannot access load() method ! why ? what should i do ?

error :

cannot read property 'load' of undefined

Solution

  • Define videoUrl in data:

    data() {
     return {
      videoUrl: 'path/to/old/video'
     }
    }
    

    The template in html:

     <video
      ref="videoPlayer"
      muted
      controls
     >
      <source :src="videoUrl" type="video/mp4" />
     </video>
    

    In a methods or a Nuxt hook:

    changeVideoUrl() {
     this.videoUrl = '/videos/home/intro-desktop.mp4'
     const videoPlayer = this.$refs.videoPlayer
     videoPlayer.load()
     videoPlayer.play()
    },
    
    

    Is important to define videoUrl in data to activate Vue reactivity system properly.