How to stop video download until a v-if condition is satisfied

Viewed 166

I have multiple video files on my actual vue project. Each video has some rule which is controlled by v-if.

If v-if is true, then only I need to download the video file.

Currently what is happening is, even though we have v-if set to false, the video file is downloaded from network. Is there a way to stop this behavior ?

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <video v-if="showVideo" autoplay loop muted width="450" src="https://www.w3schools.com/tags/movie.mp4"></video>
  <video v-if="showVideo" autoplay loop muted width="450" src="https://www.w3schools.com/tags/movie.mp4"></video>
  <div>
  </div>
</div>

Sample JS fiddle: https://jsfiddle.net/sajuthankathurai/62n5erju/26/

enter image description here

2 Answers

I'm not sure if this is the best way to do it, but this works. You can put the src path in a computed property then only bind it on the video element when showVideo is true

<div id="app">
  <video v-if="showVideo" autoplay loop muted width="450" :src="downloadSrc"></video>
  <video v-if="showVideo" autoplay loop muted width="450" :src="downloadSrc"></video>
</div>

new Vue({
  el:"#app",
  data:{
   showVideo : true
    
  },
  computed: {
    downloadSrc(){
        return this.showVideo ? 'https://www.w3schools.com/tags/movie.mp4' : '';
    }
  }
})

If you embbed your video in a template, that has the v-if property, the video tag does not seem to be evaluated on initialization:

<div id="app">
    <template v-if="showVideo">
        <video autoplay loop muted width="450" src="https://www.w3schools.com/tags/movie.mp4"></video>
        <video autoplay loop muted width="450" src="https://www.w3schools.com/tags/movie.mp4"></video>
    </template>
</div>
Related