vue 实现视频
Vue 实现视频播放功能
在 Vue 中实现视频播放功能可以通过多种方式完成,以下是几种常见的方法:
使用 HTML5 的 <video> 标签
Vue 可以直接在模板中使用 HTML5 的 <video> 标签来嵌入视频:
<template>
<div>
<video controls width="640" height="360">
<source src="path/to/video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</template>
controls属性添加播放控制条(播放/暂停、音量等)。width和height设置视频显示尺寸。<source>标签指定视频源,支持多种格式(如 MP4、WebM 等)。
使用第三方视频播放器库
如果需要更丰富的功能(如弹幕、自定义皮肤等),可以集成第三方库,例如:
-
Video.js
安装:
npm install video.js使用:
<template> <video-player :options="playerOptions" /> </template> <script> import 'video.js/dist/video-js.css'; import { videoPlayer } from 'vue-video-player'; export default { components: { videoPlayer }, data() { return { playerOptions: { sources: [{ src: 'path/to/video.mp4', type: 'video/mp4' }], controls: true } }; } }; </script> -
Vue-Video-Player
专为 Vue 封装的播放器,基于 Video.js,支持更多定制化配置。
动态加载视频源

通过 Vue 的数据绑定动态切换视频源:
<template>
<video controls :src="currentVideo"></video>
<button @click="changeVideo('new-video.mp4')">切换视频</button>
</template>
<script>
export default {
data() {
return {
currentVideo: 'default-video.mp4'
};
},
methods: {
changeVideo(src) {
this.currentVideo = src;
}
}
};
</script>
直播流支持
对于直播场景(如 HLS 或 RTMP 协议),可以使用以下库:
- HLS.js:处理 HLS 流。
- Flv.js:处理 FLV 格式的流。
示例(HLS):
<template>
<video ref="videoPlayer" controls></video>
</template>
<script>
import Hls from 'hls.js';
export default {
mounted() {
const videoSrc = 'http://example.com/live/stream.m3u8';
const video = this.$refs.videoPlayer;
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(videoSrc);
hls.attachMedia(video);
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = videoSrc;
}
}
};
</script>
注意事项
- 跨域问题:确保视频源服务器允许跨域访问(CORS 配置)。
- 移动端兼容性:部分浏览器对视频格式(如 MP4)的支持可能不同,需提供多格式备用源。
- 性能优化:大视频文件建议分片加载或使用流媒体服务。






