vue实现视频功能
Vue 实现视频播放功能
使用 Vue 实现视频功能可以通过原生 HTML5 <video> 标签或第三方库(如 video.js)来实现。以下是两种常见方法:
使用原生 HTML5 <video> 标签
在 Vue 组件中直接使用 <video> 标签,通过绑定 src 和控制方法实现基础播放功能。
<template>
<div>
<video ref="videoPlayer" controls width="640" height="360">
<source :src="videoSrc" type="video/mp4">
Your browser does not support the video tag.
</video>
<button @click="play">Play</button>
<button @click="pause">Pause</button>
</div>
</template>
<script>
export default {
data() {
return {
videoSrc: 'path/to/video.mp4'
};
},
methods: {
play() {
this.$refs.videoPlayer.play();
},
pause() {
this.$refs.videoPlayer.pause();
}
}
};
</script>
使用第三方库 video.js
video.js 是一个功能强大的视频播放器库,支持多种格式和自定义 UI。
安装依赖:
npm install video.js
在 Vue 组件中使用:
<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: {
type: Object,
default() {
return {
controls: true,
sources: [{
src: 'path/to/video.mp4',
type: 'video/mp4'
}]
};
}
}
},
mounted() {
this.player = videojs(this.$refs.videoPlayer, this.options);
},
beforeDestroy() {
if (this.player) {
this.player.dispose();
}
}
};
</script>
实现视频流播放
对于直播或实时视频流,可以使用 HLS 或 DASH 协议。以 HLS 为例,需安装 hls.js:
安装依赖:
npm install hls.js
在 Vue 组件中使用:
<template>
<div>
<video ref="videoPlayer" controls></video>
</div>
</template>
<script>
import Hls from 'hls.js';
export default {
data() {
return {
hls: null,
videoSrc: 'http://example.com/stream.m3u8'
};
},
mounted() {
if (Hls.isSupported()) {
this.hls = new Hls();
this.hls.loadSource(this.videoSrc);
this.hls.attachMedia(this.$refs.videoPlayer);
} else if (this.$refs.videoPlayer.canPlayType('application/vnd.apple.mpegurl')) {
this.$refs.videoPlayer.src = this.videoSrc;
}
},
beforeDestroy() {
if (this.hls) {
this.hls.destroy();
}
}
};
</script>
自定义视频控件
通过 Vue 的数据绑定和事件处理,可以自定义视频控件:
<template>
<div>
<video ref="videoPlayer" @timeupdate="updateProgress" width="640" height="360">
<source :src="videoSrc" type="video/mp4">
</video>
<div>
<button @click="togglePlay">{{ isPlaying ? 'Pause' : 'Play' }}</button>
<input type="range" v-model="progress" max="100" @input="seek">
</div>
</div>
</template>
<script>
export default {
data() {
return {
videoSrc: 'path/to/video.mp4',
isPlaying: false,
progress: 0
};
},
methods: {
togglePlay() {
const video = this.$refs.videoPlayer;
if (this.isPlaying) {
video.pause();
} else {
video.play();
}
this.isPlaying = !this.isPlaying;
},
updateProgress() {
const video = this.$refs.videoPlayer;
this.progress = (video.currentTime / video.duration) * 100;
},
seek(e) {
const video = this.$refs.videoPlayer;
video.currentTime = (e.target.value / 100) * video.duration;
}
}
};
</script>
注意事项
- 跨域问题:确保视频资源服务器配置了正确的 CORS 策略。
- 格式兼容性:不同浏览器支持的视频格式可能不同,需提供多种格式备用源。
- 移动端适配:移动设备可能限制自动播放,需通过用户交互触发播放。
以上方法覆盖了从基础播放到高级流媒体的常见需求,可根据实际场景选择合适方案。







