Vue3+Ts+video.js:实现自定义视频播放
<template>
<div class="video-player-container">
<video
ref="videoPlayer"
class="video-js vjs-default-skin"
controls
preload="auto"
width="640"
height="264"
data-setup="{}"
>
<source :src="videoUrl" type="video/mp4" />
</video>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, watch } from 'vue';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
export default defineComponent({
name: 'VideoPlayer',
props: {
videoUrl: {
type: String,
required: true
}
},
setup(props) {
const videoPlayer = ref<null | HTMLVideoElement>(null);
let player: videojs.Player | null = null;
onMounted(() => {
if (videoPlayer.value) {
player = videojs(videoPlayer.value, {
bigPlayButton: false,
textTrackDisplay: false,
posterImage: false,
errorDisplay: false,
controlBar: true
}, function onPlayerReady() {
console.log('Player is ready');
});
}
});
onMounted(() => {
if (player) {
player.src({ src: props.videoUrl, type: 'video/mp4' });
player.load();
}
});
watch(() => props.videoUrl, (newUrl) => {
if (player && newUrl) {
player.src({ src: newUrl, type: 'video/mp4' });
player.load();
}
});
// 组件卸载前清理资源
onUnmounted(() => {
if (player) {
player.dispose();
}
});
return { videoPlayer };
}
});
</script>
<style scoped>
.video-player-container {
/* 样式按需定制 */
}
</style>
这个代码实例展示了如何在Vue 3和TypeScript环境中结合Vue和Video.js来创建一个自定义的视频播放器组件。它使用了Composition API,包括ref
, onMounted
, watch
等来管理视频播放器的生命周期和动态更新视频源。同时,它还包含了对组件卸载前清理资源的处理,确保不会产生内存泄漏。
评论已关闭