vue实现播放视频
使用 <video> 标签嵌入视频
在 Vue 中可以直接使用 HTML5 的 <video> 标签播放视频。通过 src 属性指定视频路径,controls 属性显示播放控件。
<template>
<video controls width="600">
<source src="/path/to/video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</template>
动态绑定视频源
通过 Vue 的响应式数据动态切换视频源,使用 v-bind 绑定 src 属性。
<template>
<video controls :src="currentVideo"></video>
<button @click="changeVideo">切换视频</button>
</template>
<script>
export default {
data() {
return {
currentVideo: '/path/to/video1.mp4',
videos: ['/path/to/video1.mp4', '/path/to/video2.mp4']
}
},
methods: {
changeVideo() {
this.currentVideo = this.videos[1];
}
}
}
</script>
使用第三方库(如 Video.js)
对于更复杂的播放器功能(如自定义 UI、字幕支持),可以集成 Video.js。
安装依赖:

npm install video.js
在 Vue 中初始化 Video.js:
<template>
<video ref="videoPlayer" class="video-js"></video>
</template>
<script>
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
export default {
mounted() {
this.player = videojs(this.$refs.videoPlayer, {
controls: true,
sources: [{
src: '/path/to/video.mp4',
type: 'video/mp4'
}]
});
},
beforeDestroy() {
if (this.player) {
this.player.dispose();
}
}
}
</script>
实现视频直播(HLS/DASH)
使用 hls.js 或 dash.js 库支持流媒体协议。以 HLS 为例:

安装依赖:
npm install hls.js
集成 HLS 播放:
<template>
<video ref="videoPlayer" controls></video>
</template>
<script>
import Hls from 'hls.js';
export default {
mounted() {
const videoSrc = 'https://example.com/live/stream.m3u8';
const videoElement = this.$refs.videoPlayer;
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(videoSrc);
hls.attachMedia(videoElement);
} else if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
videoElement.src = videoSrc;
}
}
}
</script>
自定义播放器控件
通过 Vue 的指令和事件实现自定义播放、暂停等功能:
<template>
<div>
<video ref="videoPlayer" :src="videoSrc" @timeupdate="updateProgress"></video>
<button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
<input type="range" v-model="progress" max="100">
</div>
</template>
<script>
export default {
data() {
return {
videoSrc: '/path/to/video.mp4',
isPlaying: false,
progress: 0
}
},
methods: {
togglePlay() {
const video = this.$refs.videoPlayer;
this.isPlaying ? video.pause() : video.play();
this.isPlaying = !this.isPlaying;
},
updateProgress() {
const video = this.$refs.videoPlayer;
this.progress = (video.currentTime / video.duration) * 100;
}
}
}
</script>






