vue实现视频播放
Vue 实现视频播放的方法
使用 HTML5 <video> 标签
在 Vue 模板中直接使用 HTML5 的 <video> 标签,通过绑定 src 属性动态加载视频源。适合简单的视频播放需求。
<template>
<video controls :src="videoUrl" width="600"></video>
</template>
<script>
export default {
data() {
return {
videoUrl: 'https://example.com/sample.mp4'
};
}
};
</script>
使用第三方库(如 Video.js)
Video.js 是一个流行的视频播放器库,支持多种格式和自定义 UI。通过 Vue 封装组件可以更方便地集成。
安装 Video.js:
npm install video.js
封装 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, () => {
console.log('Player is ready');
});
},
beforeDestroy() {
if (this.player) {
this.player.dispose();
}
}
};
</script>
调用组件:

<template>
<VideoPlayer :options="videoOptions" />
</template>
<script>
export default {
data() {
return {
videoOptions: {
autoplay: false,
controls: true,
sources: [{
src: 'https://example.com/sample.mp4',
type: 'video/mp4'
}]
}
};
}
};
</script>
使用 Vue 专用库(如 Vue-Video-Player)
vue-video-player 是基于 Video.js 的 Vue 封装库,简化了集成步骤。
安装:
npm install vue-video-player
使用示例:

<template>
<video-player :options="playerOptions" />
</template>
<script>
import { videoPlayer } from 'vue-video-player';
import 'video.js/dist/video-js.css';
export default {
components: { videoPlayer },
data() {
return {
playerOptions: {
autoplay: false,
controls: true,
sources: [{
src: 'https://example.com/sample.mp4',
type: 'video/mp4'
}]
}
};
}
};
</script>
实现自定义控制条
通过监听 <video> 原生事件和绑定方法,可以实现自定义控制逻辑。
<template>
<div>
<video ref="video" :src="videoUrl" @timeupdate="updateProgress"></video>
<button @click="togglePlay">{{ isPlaying ? 'Pause' : 'Play' }}</button>
<input type="range" v-model="progress" max="100">
</div>
</template>
<script>
export default {
data() {
return {
videoUrl: 'https://example.com/sample.mp4',
isPlaying: false,
progress: 0
};
},
methods: {
togglePlay() {
const video = this.$refs.video;
if (this.isPlaying) {
video.pause();
} else {
video.play();
}
this.isPlaying = !this.isPlaying;
},
updateProgress() {
const video = this.$refs.video;
this.progress = (video.currentTime / video.duration) * 100;
}
}
};
</script>
流媒体支持(如 HLS/DASH)
对于流媒体协议(如 HLS 或 DASH),需使用专用库(如 hls.js 或 dash.js)。
HLS 示例(需安装 hls.js):
<template>
<video ref="video" controls></video>
</template>
<script>
import Hls from 'hls.js';
export default {
mounted() {
const videoSrc = 'https://example.com/stream.m3u8';
const video = this.$refs.video;
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 头,否则可能无法加载。
- 移动端兼容性:部分浏览器(如 iOS Safari)要求用户交互后才能触发
autoplay。 - 性能优化:大视频文件建议使用分片或流媒体协议减少初始加载时间。






