video.js是一款为HTML5世界从头构建的网络视频播放器。它支持HTML5视频和媒体源扩展,以及其他播放技术,如YouTube和Vimeo(通过插件)。它支持在台式机和移动设备上播放视频。

一、安装video.js

npm i video.js --save


二、封装组件

<template>
  <video
    ref="videoRef"
    class="video-js vjs-big-play-centered"
    controls
    preload="auto"
    data-setup="{}"
    :poster="posterImg"
  >
    <source class="video-content" :src="videoPath" type="video/mp4" />
    <p class="vjs-no-js">
      To view this video please enable JavaScript, and consider upgrading to a
      web browser that supports HTML5 video
    </p>
  </video>
</template>

<script>
import videoJs from 'video.js'
import 'video.js/dist/video-js.css'

export default {
  name: 'playerVideo',
  props: {
    posterImg: String,
    videoPath: String,
    videoOpts: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      videoPlayer: null
    }
  },
  mounted () {
    this.$nextTick(() => {
      const videoRef = this.$refs.videoRef
      if (!videoRef) {
        console.warn('未初始化Video-Dom实例')
        return false
      }

      if (!this.videoPlayer) {
        this.videoPlayer = videoJs(videoRef, this.videoOpts)
      }
    })
  },
  beforeDestroy () {
    if (this.videoPlayer) {
      this.videoPlayer.dispose()
    }
  }
}
</script>

<style scoped lang="scss">
.video-js {
  width: 100%;
  height: 100%;

  .video-content {
    object-fit: fill;
  }
}
</style>