vue视频播放实现
Vue 视频播放实现方法
使用 HTML5 <video> 标签
Vue 中可以结合原生 HTML5 的 <video> 标签实现基础视频播放功能。在模板中直接嵌入 <video> 标签,通过 Vue 的数据绑定控制视频源和播放状态。
<template>
<video ref="videoPlayer" :src="videoSource" controls></video>
</template>
<script>
export default {
data() {
return {
videoSource: 'path/to/video.mp4'
}
}
}
</script>
使用第三方视频播放器库
对于更丰富的功能(如弹幕、清晰度切换等),推荐使用成熟的第三方库:
-
Video.js
安装:npm install video.js使用示例:
<template> <video id="my-video" class="video-js" controls preload="auto"> <source :src="videoUrl" type="video/mp4"> </video> </template> <script> import videojs from 'video.js'; import 'video.js/dist/video-js.css'; export default { mounted() { videojs('my-video'); } } </script> -
Vue-Video-Player
专为 Vue 封装的播放器组件:npm install vue-video-player使用示例:
<template> <vue-video-player :options="playerOptions"></vue-video-player> </template> <script> import { videoPlayer } from 'vue-video-player'; import 'video.js/dist/video-js.css'; export default { components: { videoPlayer }, data() { return { playerOptions: { sources: [{ src: 'path/to/video.mp4', type: 'video/mp4' }] } } } } </script>
实现自定义控制条
通过 Vue 的事件绑定和方法控制,可以自定义播放器交互逻辑:
<template>
<div>
<video ref="player" :src="videoSrc"></video>
<button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
</div>
</template>
<script>
export default {
data() {
return {
videoSrc: 'video.mp4',
isPlaying: false
}
},
methods: {
togglePlay() {
const player = this.$refs.player;
this.isPlaying ? player.pause() : player.play();
this.isPlaying = !this.isPlaying;
}
}
}
</script>
直播流播放
对于直播场景(如 HLS 或 RTMP 协议),可使用以下方案:
-
HLS.js
处理.m3u8格式的直播流:npm install hls.js实现代码:
import Hls from 'hls.js'; export default { mounted() { const video = this.$refs.video; if (Hls.isSupported()) { const hls = new Hls(); hls.loadSource('http://example.com/live.m3u8'); hls.attachMedia(video); } } } -
flv.js
支持 FLV 格式的直播流:npm install flv.js实现代码:
import flvjs from 'flv.js'; export default { mounted() { if (flvjs.isSupported()) { const player = flvjs.createPlayer({ type: 'flv', url: 'http://example.com/live.flv' }); player.attachMediaElement(this.$refs.video); player.load(); } } }
注意事项
- 跨浏览器测试时需注意视频格式兼容性(MP4 兼容性最佳)。
- 移动端浏览器可能会强制全屏播放,需通过
playsinline属性解决。 - 大文件视频建议实现分段加载或流式传输。







