vue实现视频播放条
实现视频播放条的基本结构
使用 Vue 结合 HTML5 的 <video> 标签实现视频播放条的核心功能。以下是一个基础模板:
<template>
<div class="video-player">
<video
ref="videoPlayer"
@timeupdate="updateProgress"
@play="onPlay"
@pause="onPause"
>
<source :src="videoSrc" type="video/mp4">
</video>
<div class="controls">
<button @click="togglePlay">{{ isPlaying ? 'Pause' : 'Play' }}</button>
<input
type="range"
v-model="progress"
@input="seekVideo"
min="0"
max="100"
>
<span>{{ currentTimeFormatted }} / {{ durationFormatted }}</span>
</div>
</div>
</template>
数据与事件处理
在 Vue 的 data 和 methods 中定义播放条的核心逻辑:

<script>
export default {
data() {
return {
videoSrc: 'path/to/video.mp4',
isPlaying: false,
progress: 0,
currentTime: 0,
duration: 0
};
},
computed: {
currentTimeFormatted() {
return this.formatTime(this.currentTime);
},
durationFormatted() {
return this.formatTime(this.duration);
}
},
methods: {
togglePlay() {
const video = this.$refs.videoPlayer;
this.isPlaying ? video.pause() : video.play();
},
onPlay() {
this.isPlaying = true;
},
onPause() {
this.isPlaying = false;
},
updateProgress() {
const video = this.$refs.videoPlayer;
this.currentTime = video.currentTime;
this.duration = video.duration;
this.progress = (video.currentTime / video.duration) * 100;
},
seekVideo(e) {
const video = this.$refs.videoPlayer;
const seekTime = (e.target.value / 100) * video.duration;
video.currentTime = seekTime;
},
formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
}
}
};
</script>
样式优化
通过 CSS 美化播放条,确保交互友好:
<style scoped>
.video-player {
max-width: 800px;
margin: 0 auto;
position: relative;
}
video {
width: 100%;
display: block;
}
.controls {
background: #333;
padding: 10px;
display: flex;
align-items: center;
gap: 10px;
}
input[type="range"] {
flex-grow: 1;
}
button {
background: #fff;
border: none;
padding: 5px 10px;
cursor: pointer;
}
</style>
扩展功能
-
音量控制
添加音量滑块,通过video.volume属性调整:
<input type="range" v-model="volume" @input="setVolume" min="0" max="1" step="0.1" >setVolume(e) { this.$refs.videoPlayer.volume = e.target.value; } -
全屏切换
使用浏览器全屏 API:toggleFullscreen() { const video = this.$refs.videoPlayer; video.requestFullscreen?.call(video); } -
快捷键支持
监听键盘事件实现空格键播放/暂停:mounted() { document.addEventListener('keydown', (e) => { if (e.code === 'Space') this.togglePlay(); }); }






