Samir Aba
Samir Aba

Reputation: 53

HTML5 Video element in vue.js?

I am trying to use the HTML5 Video element in a vue.js application. How can I wrap the video as a data property and use it in the vue.js app.

This is my code:

<template>
  <div class="video-player">
    <video class="video">
      <source src="@/assets/video.mp4" type="video/mp4">
    </video>
</template>

<script>
export default {
  name: "VideoPlayer",
  data: {
   video: null
  }
}
</script>

Upvotes: 4

Views: 13096

Answers (2)

Hamzaouiii
Hamzaouiii

Reputation: 458

Firstly, you have forgotten a closing div tag.

The proper way to do this is by using refsand computed properties instead of data(). Just add a ref attribute to your video-tag

  <template>
      <div class="video-player">
        <video class="video" ref="video">
          <source src="@/assets/video.mp4" type="video/mp4">
        </video>
      </div>
    </template>
    
<script>
export default {
  name: "VideoPlayer",
   computed: {
    videoElement () {
      return this.$refs.video;
    }, 
  }
}
</script>

Then you can use your videoElement anywhere within the component by calling this.videoElement

Upvotes: 12

Maksym Globa
Maksym Globa

Reputation: 11

Create component in ./components/Video.vue:

<template>
  <div class="video-wrap">
    <video controls="true">
      <source :src="mp4" type="video/mp4">
    </video>
  </div>
</template>
<script>
export default {
  name: "Video",
  props: {
    mp4: String
  }
}
</script>

Import to your component:

import Video from '@/components/Video.vue'

And use dynamic URL:

<Video :mp4="require(`@/assets/video.mp4`)" />

Upvotes: 1

Related Questions