前端vue实现视频播放
Vue 实现视频播放的方法
使用 HTML5 <video> 标签
Vue 可以直接利用 HTML5 的 <video> 标签实现基础视频播放功能。通过绑定 src 和事件控制播放状态。
<template>
<div>
<video
ref="videoPlayer"
:src="videoSrc"
controls
@play="onPlay"
@pause="onPause"
></video>
<button @click="togglePlay">
{{ isPlaying ? '暂停' : '播放' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
videoSrc: 'path/to/video.mp4',
isPlaying: false
}
},
methods: {
togglePlay() {
const player = this.$refs.videoPlayer
this.isPlaying ? player.pause() : player.play()
},
onPlay() {
this.isPlaying = true
},
onPause() {
this.isPlaying = false
}
}
}
</script>
集成第三方库(如 Video.js)
对于更复杂的需求(如自定义 UI、多格式支持),可以使用 Video.js 等库。
安装依赖:
npm install video.js
示例代码:
<template>
<div>
<video ref="videoPlayer" class="video-js"></video>
</div>
</template>
<script>
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
export default {
props: ['options'],
mounted() {
this.player = videojs(
this.$refs.videoPlayer,
this.options,
function onPlayerReady() {
console.log('Player ready')
}
)
},
beforeDestroy() {
if (this.player) {
this.player.dispose()
}
}
}
</script>
使用 Vue 视频播放组件
社区提供的现成组件(如 vue-video-player)可以快速集成。
安装:
npm install vue-video-player
示例:
<template>
<vue-video-player
:options="playerOptions"
@ready="playerReadied"
/>
</template>
<script>
import { videoPlayer } from 'vue-video-player'
export default {
components: {
videoPlayer
},
data() {
return {
playerOptions: {
sources: [{
type: 'video/mp4',
src: 'path/to/video.mp4'
}],
controls: true
}
}
}
}
</script>
直播流播放(HLS/DASH)
对于直播或自适应码率视频,需使用 hls.js 或 dash.js 库。
HLS 示例:
<template>
<video ref="videoEl" controls></video>
</template>
<script>
import Hls from 'hls.js'
export default {
mounted() {
const src = 'http://example.com/stream.m3u8'
const video = this.$refs.videoEl
if (Hls.isSupported()) {
const hls = new Hls()
hls.loadSource(src)
hls.attachMedia(video)
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = src
}
}
}
</script>
自定义控件开发
通过 Vue 的响应式特性完全自定义播放器控件:
<template>
<div class="custom-player">
<video
ref="video"
:src="source"
@timeupdate="updateTime"
></video>
<div class="controls">
<progress :value="currentTime" :max="duration"></progress>
<button @click="togglePlay">{{ isPlaying ? '❚❚' : '►' }}</button>
<span>{{ formattedTime }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
source: 'video.mp4',
isPlaying: false,
currentTime: 0,
duration: 0
}
},
computed: {
formattedTime() {
return new Date(this.currentTime * 1000)
.toISOString()
.substr(11, 8)
}
},
methods: {
togglePlay() {
const video = this.$refs.video
this.isPlaying ? video.pause() : video.play()
},
updateTime(e) {
this.currentTime = e.target.currentTime
this.duration = e.target.duration
}
}
}
</script>






