vue swiper实现导航切换
使用Swiper实现Vue导航切换
安装Swiper和Vue相关依赖包
npm install swiper vue-awesome-swiper
基础配置
在Vue组件中引入Swiper核心模块和导航模块
import { Swiper, SwiperSlide } from 'swiper/vue'
import { Navigation } from 'swiper/modules'
import 'swiper/css'
import 'swiper/css/navigation'
组件模板结构
模板中使用Swiper组件并配置导航按钮
<template>
<div class="swiper-container">
<swiper
:modules="[Navigation]"
:navigation="{
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}"
>
<swiper-slide v-for="(item, index) in slides" :key="index">
<!-- 幻灯片内容 -->
</swiper-slide>
</swiper>
<!-- 导航按钮 -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
</template>
组件脚本配置
在setup函数中定义数据和返回必要内容
<script>
export default {
setup() {
const slides = [
{ id: 1, content: 'Slide 1' },
{ id: 2, content: 'Slide 2' },
{ id: 3, content: 'Slide 3' }
]
return {
Swiper,
SwiperSlide,
slides,
Navigation
}
}
}
</script>
样式定制
添加自定义样式增强导航按钮视觉效果
<style scoped>
.swiper-container {
position: relative;
}
.swiper-button-prev,
.swiper-button-next {
position: absolute;
top: 50%;
width: 40px;
height: 40px;
background-color: rgba(0,0,0,0.5);
color: white;
border-radius: 50%;
z-index: 10;
cursor: pointer;
}
.swiper-button-prev {
left: 10px;
}
.swiper-button-next {
right: 10px;
}
</style>
响应式配置
添加响应式断点配置适应不同屏幕尺寸
const breakpoints = {
640: {
slidesPerView: 2
},
1024: {
slidesPerView: 3
}
}
在Swiper组件上添加响应式配置
<swiper
:breakpoints="breakpoints"
<!-- 其他配置 -->
>
自定义导航按钮
使用slot方式自定义导航按钮
<swiper
:navigation="{
nextEl: '.custom-next',
prevEl: '.custom-prev'
}"
>
<!-- slides内容 -->
</swiper>
<button class="custom-prev">Previous</button>
<button class="custom-next">Next</button>






