用Vue3-video-play写一个播放组件
时间: 2023-05-27 07:07:36 浏览: 262
以下是一个基本的Vue3-video-play播放组件示例:
```
<template>
<div class="video-player">
<video ref="videoPlayer" :src="source" :poster="poster" @play="onPlay" @pause="onPause"></video>
<div class="controls">
<button @click="togglePlay">{{ isPlaying ? 'Pause' : 'Play' }}</button>
<div class="time">{{ currentTime }}</div>
<div class="progress">
<div class="progress-bar" :style="{ width: progress + '%' }"></div>
</div>
</div>
</div>
</template>
<script>
import { ref, computed, watchEffect } from 'vue';
export default {
name: 'Vue3VideoPlay',
props: {
source: String,
poster: String,
},
setup(props) {
const videoPlayer = ref(null);
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const progress = computed(() => {
return (currentTime.value / duration.value) * 100;
});
const togglePlay = () => {
if (isPlaying.value) {
videoPlayer.value.pause();
} else {
videoPlayer.value.play();
}
isPlaying.value = !isPlaying.value;
};
const onPlay = () => {
isPlaying.value = true;
};
const onPause = () => {
isPlaying.value = false;
};
watchEffect(() => {
duration.value = videoPlayer.value.duration;
});
watchEffect(() => {
currentTime.value = videoPlayer.value.currentTime;
});
return {
videoPlayer,
isPlaying,
currentTime: computed(() => formatTime(currentTime.value)),
duration: computed(() => formatTime(duration.value)),
progress,
togglePlay,
onPlay,
onPause,
};
},
methods: {
formatTime(time) {
const minutes = Math.floor(time / 60);
const seconds = Math.round(time % 60);
return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
},
},
};
</script>
<style>
.video-player {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%; /* 16:9 aspect ratio */
}
.video-player video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: fill;
}
.video-player .controls {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 50px;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 10px;
}
.video-player .controls button {
background-color: transparent;
color: #fff;
border: none;
cursor: pointer;
font-size: 14px;
}
.video-player .controls .time {
color: #fff;
font-size: 14px;
}
.video-player .controls .progress {
width: 60%;
height: 4px;
border-radius: 2px;
background-color: rgba(255, 255, 255, 0.5);
position: relative;
}
.video-player .controls .progress .progress-bar {
height: 100%;
border-radius: 2px;
background-color: #fff;
position: absolute;
top: 0;
left: 0;
}
</style>
```
该组件包含以下功能:
1. 视频播放和暂停
2. 视频当前时间和总时间的显示
3. 视频进度条的显示和拖动
4. 视频播放和暂停按钮的切换
5. 视频播放和暂停时的状态切换
可以通过以下方式使用该组件:
```
<template>
<Vue3VideoPlay source="https://example.com/video.mp4" poster="https://example.com/poster.jpg"></Vue3VideoPlay>
</template>
<script>
import Vue3VideoPlay from '@/components/Vue3VideoPlay';
export default {
name: 'App',
components: {
Vue3VideoPlay,
},
};
</script>
```
阅读全文