vue 实现视频
Vue 实现视频播放功能
使用 Vue 实现视频播放功能可以通过 HTML5 的 <video> 标签或第三方库(如 video.js)来实现。以下是两种常见的方法:
使用 HTML5 <video> 标签
HTML5 提供了原生视频播放支持,可以直接在 Vue 组件中使用 <video> 标签。
<template>
<div>
<video controls width="640" height="360">
<source src="your-video-url.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</template>
<script>
export default {
name: 'VideoPlayer',
};
</script>
controls属性显示视频控制条(播放、暂停、音量等)。width和height设置视频显示尺寸。<source>标签指定视频源文件及其类型。
使用第三方库 video.js
video.js 是一个功能强大的视频播放库,支持多种格式和自定义样式。

安装 video.js:
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 {
name: 'VideoPlayer',
props: {
options: {
type: Object,
default() {
return {
autoplay: false,
controls: true,
sources: [{
src: 'your-video-url.mp4',
type: 'video/mp4'
}]
};
}
}
},
mounted() {
this.player = videojs(this.$refs.videoPlayer, this.options, function onPlayerReady() {
console.log('Player is ready');
});
},
beforeDestroy() {
if (this.player) {
this.player.dispose();
}
}
};
</script>
<style>
.video-js {
width: 640px;
height: 360px;
}
</style>
options对象配置播放器行为(如自动播放、控制条等)。mounted钩子初始化播放器。beforeDestroy钩子清理播放器实例。
动态加载视频源
如果需要动态加载视频源,可以通过 props 或 data 传递视频 URL。
<template>
<div>
<video :src="videoUrl" controls width="640" height="360"></video>
</div>
</template>
<script>
export default {
name: 'DynamicVideoPlayer',
data() {
return {
videoUrl: 'your-video-url.mp4'
};
},
methods: {
updateVideoUrl(newUrl) {
this.videoUrl = newUrl;
}
}
};
</script>
自定义控制条
通过监听 <video> 事件和自定义按钮,可以实现更灵活的控制逻辑。
<template>
<div>
<video ref="video" width="640" height="360" @play="onPlay" @pause="onPause"></video>
<button @click="togglePlay">{{ isPlaying ? 'Pause' : 'Play' }}</button>
</div>
</template>
<script>
export default {
name: 'CustomVideoPlayer',
data() {
return {
isPlaying: false
};
},
methods: {
togglePlay() {
const video = this.$refs.video;
if (this.isPlaying) {
video.pause();
} else {
video.play();
}
},
onPlay() {
this.isPlaying = true;
},
onPause() {
this.isPlaying = false;
}
}
};
</script>
注意事项
- 跨域问题:如果视频资源位于不同域名下,需确保服务器配置了 CORS 头。
- 格式兼容性:不同浏览器支持的视频格式可能不同,建议提供多种格式源(如 MP4、WebM)。
- 移动端适配:移动设备可能限制自动播放,需用户交互触发播放。






