vue实现播放视频
使用 <video> 标签实现基础播放
在 Vue 模板中直接使用 HTML5 的 <video> 标签,通过 ref 绑定控制播放状态:
<template>
<div>
<video ref="videoPlayer" controls width="600">
<source src="/path/to/video.mp4" type="video/mp4">
</video>
<button @click="play">播放</button>
<button @click="pause">暂停</button>
</div>
</template>
<script>
export default {
methods: {
play() {
this.$refs.videoPlayer.play()
},
pause() {
this.$refs.videoPlayer.pause()
}
}
}
</script>
通过第三方库实现高级功能
安装 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)
},
beforeDestroy() {
if (this.player) {
this.player.dispose()
}
}
}
</script>
调用示例:
<VideoPlayer :options="{
autoplay: false,
controls: true,
sources: [{
src: '/path/to/video.mp4',
type: 'video/mp4'
}]
}"/>
处理直播流媒体
使用 hls.js 播放 m3u8 格式的直播流:

npm install hls.js
实现代码:
<template>
<video ref="videoPlayer" controls></video>
</template>
<script>
import Hls from 'hls.js'
export default {
data() {
return {
hls: null
}
},
mounted() {
if (Hls.isSupported()) {
const video = this.$refs.videoPlayer
this.hls = new Hls()
this.hls.loadSource('http://example.com/live.m3u8')
this.hls.attachMedia(video)
}
},
beforeDestroy() {
if (this.hls) {
this.hls.destroy()
}
}
}
</script>
实现自定义播放器控件
通过 Vue 数据绑定实现进度条控制:
<template>
<div>
<video
ref="videoPlayer"
@timeupdate="updateProgress"
@loadedmetadata="setDuration">
</video>
<input
type="range"
v-model="progress"
@input="seekTo">
</div>
</template>
<script>
export default {
data() {
return {
progress: 0,
duration: 0
}
},
methods: {
updateProgress() {
const video = this.$refs.videoPlayer
this.progress = (video.currentTime / this.duration) * 100
},
setDuration() {
this.duration = this.$refs.videoPlayer.duration
},
seekTo() {
const video = this.$refs.videoPlayer
video.currentTime = (this.progress / 100) * this.duration
}
}
}
</script>
响应式视频尺寸处理
通过 CSS 和 Vue 结合实现响应式布局:
<template>
<div class="video-container">
<video ref="videoPlayer" :style="videoStyle"></video>
</div>
</template>
<script>
export default {
data() {
return {
windowWidth: window.innerWidth
}
},
computed: {
videoStyle() {
return {
width: this.windowWidth > 768 ? '800px' : '100%',
height: this.windowWidth > 768 ? '450px' : 'auto'
}
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.windowWidth = window.innerWidth
}
}
}
</script>
<style>
.video-container {
position: relative;
padding-bottom: 56.25%; /* 16:9 Aspect Ratio */
}
.video-container video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>






