前端vue实现视频播放
使用原生HTML5视频标签
在Vue中可以直接使用HTML5的<video>标签实现基础视频播放功能。这种方式简单快捷,适合不需要复杂交互的场景。
<template>
<video controls width="600">
<source src="video.mp4" type="video/mp4">
您的浏览器不支持HTML5视频
</video>
</template>
controls属性会显示默认播放控件,包括播放/暂停、音量、全屏等。可以设置width和height控制视频尺寸。
集成第三方播放器库
对于需要更多功能和更好兼容性的场景,推荐使用专业播放器库:
- Video.js
安装依赖:npm install video.js @videojs-player/vue
使用示例:
import { defineComponent } from 'vue'
import { VideoJsPlayer } from '@videojs-player/vue'
import 'video.js/dist/video-js.css'
export default defineComponent({
components: { VideoJsPlayer },
setup() {
const options = {
autoplay: false,
controls: true,
sources: [{
src: 'video.mp4',
type: 'video/mp4'
}]
}
return { options }
}
})
- vue-video-player
基于Video.js的Vue封装:npm install vue-video-player
import VueVideoPlayer from 'vue-video-player'
import 'video.js/dist/video-js.css'
const app = createApp(App)
app.use(VueVideoPlayer)
实现自定义播放器控件
通过Vue的响应式特性可以构建自定义控制界面:

<template>
<div class="video-container">
<video ref="videoPlayer" @timeupdate="updateTime">
<source src="video.mp4" type="video/mp4">
</video>
<div class="controls">
<button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
<input type="range" v-model="progress" @input="seek">
<span>{{ currentTime }} / {{ duration }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isPlaying: false,
currentTime: 0,
duration: 0,
progress: 0
}
},
methods: {
togglePlay() {
const video = this.$refs.videoPlayer
this.isPlaying ? video.pause() : video.play()
this.isPlaying = !this.isPlaying
},
updateTime() {
const video = this.$refs.videoPlayer
this.currentTime = video.currentTime
this.duration = video.duration
this.progress = (video.currentTime / video.duration) * 100
},
seek(e) {
const video = this.$refs.videoPlayer
video.currentTime = (e.target.value / 100) * video.duration
}
}
}
</script>
处理视频格式兼容性
不同浏览器支持的视频格式不同,建议提供多种格式源:
<video controls>
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
<source src="video.ogv" type="video/ogg">
</video>
实现全屏功能
现代浏览器提供了Fullscreen API:
methods: {
toggleFullscreen() {
const video = this.$refs.videoPlayer
if (!document.fullscreenElement) {
video.requestFullscreen()
} else {
document.exitFullscreen()
}
}
}
添加字幕支持
通过<track>元素可以添加字幕:

<video controls>
<source src="video.mp4" type="video/mp4">
<track
src="subtitles.vtt"
kind="subtitles"
srclang="zh"
label="中文"
default>
</video>
字幕文件格式为WebVTT:
WEBVTT
00:00:01.000 --> 00:00:04.000
这是第一句字幕
00:00:05.000 --> 00:00:08.000
这是第二句字幕
响应式视频布局
使用CSS确保视频在不同设备上正确显示:
.video-container {
position: relative;
padding-bottom: 56.25%; /* 16:9宽高比 */
height: 0;
overflow: hidden;
}
.video-container video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
视频预加载优化
通过preload属性控制视频加载策略:
<video preload="auto"> <!-- 自动预加载 -->
<video preload="metadata"> <!-- 只加载元数据 -->
<video preload="none"> <!-- 不预加载 -->
对于长视频,可以使用MediaSource Extensions实现分段加载。






