Vue3封装Video.js组件(基于video.js)
Vue3封装Video.js组件(基于video.js)
·
Vue3封装Video.js组件
话不多说直接上代码
在项目中安装Video.js
通过npm安装video.js
npm install video.js --save
Video.js组件的封装
<template>
<div class="videoPlay">
<video
ref="m3u8_video"
class="video-js vjs-default-skin vjs-big-play-centered"
controls
>
<source :src="videoSrc" />
</video>
</div>
</template>
<script lang="ts" setup>
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import videojs, { VideoJsPlayer } from "video.js";
import "video.js/dist/video-js.css";
import zh from "video.js/dist/lang/zh-CN.json";
const props = withDefaults(
defineProps<{
videoSrc: string;
autoPlay?: boolean;
}>(),
{ autoPlay: false }
);
const m3u8_video = ref();
let player: VideoJsPlayer;
const initPlay = async () => {
videojs.addLanguage("zh-CN", zh);
await nextTick();
const options = {
muted: true,
controls: true,
autoplay: true,
loop: true,
language: "zh-CN",
techOrder: ["html5"],
};
player = videojs(m3u8_video.value, options, () => {
videojs.log("播放器已经准备好了!");
if (props.autoPlay && props.videoSrc) {
player.play();
}
player.on("ended", () => {
videojs.log("播放结束了!");
});
player.on("error", () => {
videojs.log("播放器解析出错!");
});
});
};
onMounted(() => {
initPlay();
});
//直接改变路径测试
watch(
() => props.videoSrc,
() => {
player.pause();
player.src(props.videoSrc);
player.load();
if (props.videoSrc) {
player.play();
}
}
);
onBeforeUnmount(() => {
player?.dispose();
});
</script>
<style lang="scss" scoped>
.videoPlay {
width: 100%;
height: 100%;
.video-js {
height: 100%;
width: 100%;
object-fit: fill;
}
}
:deep(.vjs-tech) {
object-fit: fill;
}
</style>
Video.js组件的使用
传入videoSrc和autoPlay参数,这里videoSrc是一段测试地址,你可以换成自己的实际视频流地址
<template>
<div class="myVideo"><VideoJs :videoSrc="data.videoSrc" autoPlay /></div>
</template>
<script lang="ts" setup>
import { reactive } from "vue";
//找到你的组件地址引入进来
import VideoJs from "@/components/video/VideoJs.vue";
const data = reactive({
videoSrc: "https://www.w3schools.com/html/movie.mp4",
});
</script>
<style scoped lang="scss">
.myVideo {
width: 100%;
height: 100%;
}
</style>
效果图(视频源有点糊,各位看官见笑了)
总结
一直在不断前进,如有问题,请各位看官指出,相互交流学习。
更多推荐
已为社区贡献3条内容
所有评论(0)