vue 实现视频
在Vue中实现视频功能可以通过多种方式完成,包括使用原生HTML5 <video>标签、第三方库或插件。以下是几种常见的方法:
使用HTML5 <video>标签
Vue支持直接使用HTML5的<video>标签来嵌入视频。这种方式简单且无需额外依赖。
<template>
<div>
<video width="320" height="240" controls>
<source src="path/to/video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</template>
使用第三方库(如Video.js)
Video.js是一个流行的视频播放器库,支持多种格式和自定义样式。
安装Video.js:
npm install video.js
在Vue组件中使用:

<template>
<div>
<video-player
ref="videoPlayer"
class="video-player vjs-default-skin"
:options="playerOptions"
></video-player>
</div>
</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: 'path/to/video.mp4',
type: 'video/mp4'
}]
}
};
}
};
</script>
使用Vue插件(如vue-video-player)
vue-video-player是一个专为Vue设计的视频播放器插件,基于Video.js。
安装:
npm install vue-video-player
示例代码:

<template>
<div>
<video-player
:options="playerOptions"
@ready="onPlayerReady"
></video-player>
</div>
</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: 'path/to/video.mp4',
type: 'video/mp4'
}]
}
};
},
methods: {
onPlayerReady(player) {
console.log('Player is ready', player);
}
}
};
</script>
实现自定义视频控件
如果需要自定义视频控件,可以通过监听<video>标签的事件和方法来实现。
<template>
<div>
<video
ref="videoPlayer"
width="320"
height="240"
@play="onPlay"
@pause="onPause"
>
<source src="path/to/video.mp4" type="video/mp4">
</video>
<button @click="playVideo">Play</button>
<button @click="pauseVideo">Pause</button>
</div>
</template>
<script>
export default {
methods: {
playVideo() {
this.$refs.videoPlayer.play();
},
pauseVideo() {
this.$refs.videoPlayer.pause();
},
onPlay() {
console.log('Video started playing');
},
onPause() {
console.log('Video paused');
}
}
};
</script>
视频流(如HLS或DASH)
对于流媒体视频(如HLS或DASH),可以使用hls.js或dash.js库。
安装hls.js:
npm install hls.js
示例代码:
<template>
<div>
<video ref="videoPlayer" controls></video>
</div>
</template>
<script>
import Hls from 'hls.js';
export default {
mounted() {
const videoSrc = 'path/to/video.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>
以上方法覆盖了从基础到高级的视频实现需求,可以根据项目需求选择合适的方式。






