vue项目实现视频
视频播放基础实现
在Vue项目中实现视频播放,可以使用HTML5的<video>标签。以下是一个基础示例:
<template>
<div>
<video controls width="600">
<source src="/path/to/video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</template>
controls属性显示默认播放控件(播放/暂停、进度条等)。src指定视频路径,可以是本地路径或远程URL。- 多格式支持可添加多个
<source>标签以兼容不同浏览器。
动态视频源绑定
通过Vue的响应式数据动态绑定视频源:
<template>
<div>
<video controls :src="videoSource"></video>
<button @click="changeVideo">切换视频</button>
</div>
</template>
<script>
export default {
data() {
return {
videoSource: '/path/to/video1.mp4'
};
},
methods: {
changeVideo() {
this.videoSource = '/path/to/video2.mp4';
}
}
};
</script>
使用第三方库增强功能
若需高级功能(如自定义控件、弹幕、倍速播放等),可集成第三方库:

-
Video.js
安装:npm install video.js
示例:<template> <video id="my-video" class="video-js" controls> <source src="/path/to/video.mp4" 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封装的播放器,基于Video.js:
安装: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>
流媒体协议支持(HLS/DASH)
播放HLS(.m3u8)或DASH(.mpd)格式的流媒体:
-
HLS.js(适用于HLS)
安装:npm install hls.js
示例:import Hls from 'hls.js'; mounted() { const video = this.$refs.video; if (Hls.isSupported()) { const hls = new Hls(); hls.loadSource('http://example.com/stream.m3u8'); hls.attachMedia(video); } else if (video.canPlayType('application/vnd.apple.mpegurl')) { video.src = 'http://example.com/stream.m3u8'; } }
自定义播放器控件
通过监听<video>事件实现自定义UI:
<template>
<div>
<video ref="video" @timeupdate="updateProgress"></video>
<div class="progress-bar" :style="{ width: progress + '%' }"></div>
<button @click="togglePlay">{{ isPlaying ? 'Pause' : 'Play' }}</button>
</div>
</template>
<script>
export default {
data() {
return {
isPlaying: false,
progress: 0
};
},
methods: {
togglePlay() {
const video = this.$refs.video;
this.isPlaying ? video.pause() : video.play();
this.isPlaying = !this.isPlaying;
},
updateProgress() {
const video = this.$refs.video;
this.progress = (video.currentTime / video.duration) * 100;
}
}
};
</script>
跨域与CDN优化
- 若视频资源跨域,确保服务器配置CORS头(如
Access-Control-Allow-Origin)。 - 使用CDN加速视频加载,例如阿里云OSS或AWS CloudFront。
移动端适配
- 添加
playsinline属性防止iOS全屏播放:<video controls playsinline></video> - 响应式尺寸通过CSS控制:
video { max-width: 100%; height: auto; }






