vue实现视频轮播功能
使用Swiper组件实现视频轮播
安装Swiper依赖包
npm install swiper vue-awesome-swiper
引入Swiper组件
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import 'swiper/css/pagination'
import 'swiper/css/navigation'
基础模板结构
<template>
<swiper
:pagination="{
clickable: true,
}"
:navigation="true"
class="mySwiper"
>
<swiper-slide v-for="(video, index) in videos" :key="index">
<video controls>
<source :src="video.src" type="video/mp4">
</video>
</swiper-slide>
</swiper>
</template>
数据定义
data() {
return {
videos: [
{ src: '/videos/video1.mp4' },
{ src: '/videos/video2.mp4' },
{ src: '/videos/video3.mp4' }
]
}
}
自定义视频控制逻辑
添加自动播放功能
const swiperOptions = {
autoplay: {
delay: 3000,
disableOnInteraction: false,
},
loop: true
}
视频播放状态管理
methods: {
onSlideChange(swiper) {
const activeSlide = swiper.slides[swiper.activeIndex]
const video = activeSlide.querySelector('video')
video.play()
swiper.slides.forEach((slide, index) => {
if(index !== swiper.activeIndex) {
const v = slide.querySelector('video')
v.pause()
v.currentTime = 0
}
})
}
}
响应式设计配置
设置不同断点的幻灯片数量
const swiperOptions = {
breakpoints: {
320: {
slidesPerView: 1
},
768: {
slidesPerView: 2
},
1024: {
slidesPerView: 3
}
}
}
性能优化方案
懒加载视频资源
<video controls preload="none">
<source :src="video.src" type="video/mp4">
</video>
添加加载状态指示
data() {
return {
loading: true
}
},
methods: {
videoLoaded() {
this.loading = false
}
}
完整组件示例
<template>
<div class="video-carousel">
<swiper
:options="swiperOptions"
@slideChange="onSlideChange"
>
<swiper-slide v-for="(video, index) in videos" :key="index">
<div v-if="loading" class="loading-spinner"></div>
<video
controls
preload="none"
@loadeddata="videoLoaded"
>
<source :src="video.src" type="video/mp4">
</video>
</swiper-slide>
</swiper>
</div>
</template>
<script>
export default {
data() {
return {
loading: true,
videos: [...],
swiperOptions: {
autoplay: { delay: 5000 },
navigation: true,
pagination: { clickable: true },
breakpoints: {...}
}
}
},
methods: {...}
}
</script>
<style>
.video-carousel {
max-width: 800px;
margin: 0 auto;
}
.swiper-slide video {
width: 100%;
height: auto;
}
</style>






