videojs vue 动态source_手把手从零开始封装一个vue视频播放器组件
时间: 2023-06-25 20:05:23 浏览: 236
好的,下面是从零开始封装一个基于videojs和Vue的动态source的视频播放器组件的步骤:
1. 安装video.js和vue-video-player
使用npm安装video.js和vue-video-player:
```
npm install video.js vue-video-player --save
```
2. 创建Vue组件
在src/components目录下创建一个VideoPlayer.vue的文件,该文件包含以下内容:
```html
<template>
<div>
<video ref="videoPlayer" class="video-js vjs-default-skin vjs-big-play-centered"></video>
</div>
</template>
<script>
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import 'vue-video-player/src/custom-theme.css';
import 'vue-video-player/src/font/font.css';
import 'vue-video-player/src/assets/video-player.css';
export default {
name: 'VideoPlayer',
props: {
sources: {
type: Array,
required: true
},
options: {
type: Object,
default: () => ({})
}
},
mounted() {
this.initPlayer();
},
beforeDestroy() {
if (this.player) {
this.player.dispose();
}
},
methods: {
initPlayer() {
const video = this.$refs.videoPlayer;
const playerOptions = Object.assign({
controlBar: {
children: {
playToggle: {},
progressControl: {},
remainingTimeDisplay: {},
fullscreenToggle: {}
}
},
sources: this.sources
}, this.options);
this.player = videojs(video, playerOptions, function onPlayerReady() {
console.log('Player ready');
});
}
}
};
</script>
```
3. 在Vue项目中使用该组件
在需要使用视频播放器的Vue组件中引入VideoPlayer组件,并传入sources和options参数:
```html
<template>
<div class="app">
<VideoPlayer :sources="sources" :options="options"></VideoPlayer>
</div>
</template>
<script>
import VideoPlayer from '@/components/VideoPlayer.vue';
export default {
name: 'App',
components: {
VideoPlayer
},
data() {
return {
sources: [
{
src: 'http://example.com/path/to/video.mp4',
type: 'video/mp4'
}
],
options: {
autoplay: false,
controls: true,
preload: 'auto',
fluid: true
}
};
}
};
</script>
```
这样就完成了从零开始封装一个基于videojs和Vue的动态source的视频播放器组件。
阅读全文