Swiper10.2.0版本在vue3中的使用方法
1.简单使用示例
vue代码
<template>
<swiper :pagination="true" :modules="modules" class="mySwiper">
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide><swiper-slide>Slide 3</swiper-slide>
<swiper-slide>Slide 4</swiper-slide><swiper-slide>Slide 5</swiper-slide>
<swiper-slide>Slide 6</swiper-slide><swiper-slide>Slide 7</swiper-slide>
<swiper-slide>Slide 8</swiper-slide><swiper-slide>Slide 9</swiper-slide>
</swiper>
</template>
<script setup>
// Import Swiper Vue.js components
import { Swiper, SwiperSlide } from 'swiper/vue';
// Import Swiper styles
import 'swiper/css';
import 'swiper/css/pagination';
import './style.css';
// import required modules
import { Pagination } from 'swiper/modules';
const modules=[Pagination]
</script>
style.css文件
#app {
height: 100%;
}
html,
body {
position: relative;
height: 100%;
}
body {
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color: #000;
margin: 0;
padding: 0;
}
.swiper {
width: 100%;
height: 100%;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
/* Center slide text vertically */
display: flex;
justify-content: center;
align-items: center;
}
.swiper-slide img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
2.一些功能
①分页器:pagination="true" 需要导入模块
②自由模式 :freeMode="true" 需要导入模块
③自动播放 :autoplay="{ delay: 2500, disableOnInteraction: false, pauseOnMouseEnter:true }" 需要导入模块
④ 设置可通过鼠标滚动切换 :mousewheel= "true" 需要导入
⑤设置垂直方向的滚动跳转 :direction="'vertical'" 不需要导入
⑥swiper的嵌套 需要给你的swiper添加类名 class="mySwiper swiper-v" 嵌套里面的swiper就写mySwiper2 swiper-h
以下是代码示例:
<swiper
:direction="'vertical'"
:freeMode="true"
:mousewheel= "true"
:modules="modules"
@scroll="scrollY"
:loop="false"
:slidesPerView="'auto'"
@swiper="onSwiper"
class="mySwiper swiper-v" >
3.我使用swiper遇到的一些问题
①获取swiper实例
因为在vue3语法糖中是不用创建组件实例的,所以需要获取实例的话就需要使用@swiper="onSwiper"
let useSwiper = ref(null);
const onSwiper = (swiper) => {
// console.log(swiper);
useSwiper.value = swiper
};
②监听鼠标滚动事件
直接添加 @scroll="scrollY 然后在下面写方法
const scrollY=(e)=>{
// console.log(e.translate,e.realIndex);
if(e.realIndex>=1){
showtop.value=true
}else{
showtop.value=false
}
}
③使用grid网格布局时调节每一个swiper-slide的高度,确保一列有两个
.swiper-slide{
height: 48%;}