封装videoJS,可以作为Vue组件使用

封装子组件

<script>
// 引入video.js先关的js和css
import videojs from 'video.js'
import "video.js/dist/video-js.min.css"
import video_zhCN from 'video.js/dist/lang/zh-CN.json'
videojs.addLanguage('zh-CN', video_zhCN)
export default {
  name: 'VideoJs',
  props: {
    url: {
      // 父组件传过来的视频链接
      type: String,
      default: '',
    },
    id: {
      // 父组件传过来的视频序号
      type: String,
      default: null,
    },
  },
  mounted(){
    // 添加初始化宽和高,否则加载播放器的时候会闪一下
    let options = {
      width:960,
      height:400,
      language: "zh-CN",
    }
    let that = this
    let player = videojs(this.$refs.videojs, options, function onPlayerReady() {
      videojs.log('播放器准备好了!');

      // 最新的浏览器一般禁止video自动播放,直接调用play()会报错。只有用户在页面上操作后或者在video标签上添加muted(静音)属性,才能调用play函数。本案例是在video标签上添加了muted属性。
      this.on('ended', function() {
        videojs.log('播放结束!');
        that.$emit('ended', that.id)
      });
      // 解决出现因网络问题需要重新加载视频问题,提示错误:A network error caused the media download to fail part-way.
      this.reloadSourceOnError({
        // getSource allows you to override the source object used when an error occurs
        getSource: function(reload) {
          console.log('Reloading because of an error');

          // call reload() with a fresh source object
          // you can do this step asynchronously if you want (but the error dialog will
          // show up while you're waiting)
          reload({
            src: that.url + '?rnd=' + new Date().getTime()
            // type: 'application/x-mpegURL'
          });
        },

        // errorInterval specifies the minimum amount of seconds that must pass before
        // another reload will be attempted
        errorInterval: 5
      });
    }, {passive: false});
  }
}
</script>

<template>
  <div>
    <video
      ref="videojs"
      class="video-js"
      controls
      preload="auto"
      data-setup='{}'
      muted
    >
      <source :src="this.url + '?rnd=' + new Date().getTime()" type="video/mp4"/>
    </video>
  </div>
</template>
<style scoped>
.video-js {
  width: 100% !important;
  height: 100% !important;
}
</style>


在父组件引入使用:

<VideoJs style="width: 100%;height: 100%;" :id="'video' + index" @ended="endedHandle" :url="ossUrl + item.url"></VideoJs>

你可能感兴趣的:(前端,vue.js,js,vue.js,前端,javascript)