vue实现视频播放条
Vue 实现视频播放进度条
在 Vue 中实现视频播放进度条需要结合 HTML5 的 <video> 元素和 Vue 的数据绑定功能。以下是一个完整的实现方案。
基础结构
创建一个 Vue 组件,包含视频元素和进度条控件。
<template>
<div class="video-player">
<video
ref="videoPlayer"
@timeupdate="updateProgress"
@loadedmetadata="setDuration"
>
<source :src="videoSrc" type="video/mp4">
</video>
<div class="controls">
<input
type="range"
v-model="progress"
@input="seekVideo"
min="0"
:max="duration"
>
</div>
</div>
</template>
核心逻辑
在 Vue 的 script 部分实现播放控制逻辑。
<script>
export default {
data() {
return {
videoSrc: 'your-video.mp4',
progress: 0,
duration: 0
}
},
methods: {
updateProgress() {
this.progress = this.$refs.videoPlayer.currentTime;
},
seekVideo() {
this.$refs.videoPlayer.currentTime = this.progress;
},
setDuration() {
this.duration = this.$refs.videoPlayer.duration;
}
}
}
</script>
样式优化
添加基础样式提升用户体验。
<style scoped>
.video-player {
position: relative;
width: 100%;
max-width: 800px;
}
video {
width: 100%;
}
.controls {
background: rgba(0,0,0,0.5);
padding: 10px;
}
input[type="range"] {
width: 100%;
}
</style>
扩展功能
添加播放/暂停按钮和控制面板。
<div class="controls">
<button @click="togglePlay">
{{ isPlaying ? 'Pause' : 'Play' }}
</button>
<input
type="range"
v-model="progress"
@input="seekVideo"
min="0"
:max="duration"
>
<span>{{ formatTime(progress) }} / {{ formatTime(duration) }}</span>
</div>
data() {
return {
isPlaying: false
}
},
methods: {
togglePlay() {
const video = this.$refs.videoPlayer;
if (video.paused) {
video.play();
this.isPlaying = true;
} else {
video.pause();
this.isPlaying = false;
}
},
formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${minutes}:${secs < 10 ? '0' : ''}${secs}`;
}
}
注意事项
- 确保视频文件路径正确
- 跨浏览器测试视频格式兼容性
- 移动端需要添加触摸事件支持
- 考虑添加缓冲进度显示
- 可以引入第三方库如 video.js 获得更完整功能
这个实现提供了视频播放的核心功能,可以根据需要进一步扩展其他特性如全屏控制、音量调节等。







