vue实现轮播视频
Vue 实现轮播视频的方法
使用第三方库(推荐)
安装 vue-awesome-swiper 或 swiper 库,它们支持视频嵌入和轮播功能。以下是基于 vue-awesome-swiper 的实现:
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(video, index) in videos" :key="index">
<video controls :poster="video.poster" class="video-slide">
<source :src="video.src" type="video/mp4">
</video>
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
import 'swiper/css/swiper.css';
export default {
components: { Swiper, SwiperSlide },
data() {
return {
videos: [
{ src: '/path/to/video1.mp4', poster: '/path/to/poster1.jpg' },
{ src: '/path/to/video2.mp4', poster: '/path/to/poster2.jpg' }
],
swiperOptions: {
pagination: { el: '.swiper-pagination' },
loop: true,
autoplay: { delay: 3000, disableOnInteraction: false }
}
};
}
};
</script>
<style scoped>
.video-slide {
width: 100%;
height: auto;
}
</style>
自定义实现
通过 Vue 的 v-for 和动态样式控制,手动切换视频:
<template>
<div class="video-carousel">
<div class="video-container">
<video
v-for="(video, index) in videos"
:key="index"
:ref="'video' + index"
:class="{ active: currentIndex === index }"
controls
:poster="video.poster"
>
<source :src="video.src" type="video/mp4">
</video>
</div>
<button @click="prev">上一页</button>
<button @click="next">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
videos: [
{ src: '/path/to/video1.mp4', poster: '/path/to/poster1.jpg' },
{ src: '/path/to/video2.mp4', poster: '/path/to/poster2.jpg' }
],
currentIndex: 0
};
},
methods: {
next() {
this.currentIndex = (this.currentIndex + 1) % this.videos.length;
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.videos.length) % this.videos.length;
}
}
};
</script>
<style scoped>
.video-container {
position: relative;
width: 100%;
height: 400px;
overflow: hidden;
}
video {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s;
}
video.active {
opacity: 1;
}
</style>
关键点
- 视频预加载:通过
poster属性设置封面图,避免空白等待。 - 自动播放:在
swiperOptions中配置autoplay,或通过setInterval控制自定义轮播。 - 交互暂停:监听
mouseenter和mouseleave事件暂停/恢复轮播。
注意事项
- 移动端需添加
playsinline属性避免全屏播放。 - 视频格式优先选择兼容性强的
mp4,并提供备用格式(如WebM)。







