效果图
需求展示:右上角可左右滑动并控制遮罩层显示隐藏;每行显示4个,每次滑动4个
安装
npm install Swiper
yarn add Swiper
pnpm add Swiper
代码
template
<!-- 控制分页 -->
<div class="btn" @click="addPage(-1)">
<img src="@/assets/temp/btn-pageforward.svg" alt="" />
<transition name="dialog">
<div class="mask" v-show="isShowLeftMask"></div>
</transition>
</div>
<div class="btn" @click="addPage(1)">
<img src="@/assets/temp/btn-pageback.svg" alt="" />
<transition name="dialog">
<div class="mask" v-show="isShowRightMask"></div>
</transition>
</div>
...其他样式根据ui设计来
<!-- swiper 组件 -->
<Swiper
@swiper="onSwiper"
@slideChange="onSlideChange"
:modules="[Virtual]"
:slides-per-group="4"
:slides-per-view="4"
:space-between="20"
virtual
>
<SwiperSlide v-for="(item, index) in workList" :key="index" :virtualIndex="index">
<WorksCard :item="item" />
</SwiperSlide>
</Swiper>
script
// Import Swiper Vue.js components
import { Swiper, SwiperSlide } from "swiper/vue";
import { Virtual } from "swiper";
// Import Swiper styles
import "swiper/css";
// 总页数,根据你接口返回设置 Math.ceil(workList.value.length / pageSize.value);
const totalPage = ref<number>(0);
const pageSize = ref<number>(4); // 每页显示数量
const page = ref<number>(1); // 当前页码
let useSwiper: any = null; // swiper实例
// 初始化swiper
const onSwiper = (swiper: any) => {
useSwiper = swiper;
};
// 滑动事件记录分页
const onSlideChange = () => {
console.log("page", useSwiper.activeIndex / 4 + 1); // 页码
page.value = useSwiper.realIndex / pageSize.value + 1;
};
// 是否显示遮罩
const isShowLeftMask = computed(() => {
return page.value == 1;
});
const isShowRightMask = computed(() => {
return page.value == totalPage.value;
});
// 分页
const addPage = (num: number) => {
if (num > 0) {
useSwiper.slideNext();
} else if (num < 0) {
useSwiper.slidePrev();
}
};
更多内容请参考以下
【swiper 官方】在 vue 中使用 swiper
【swiper 官方】中文 API 文档
【CSDN】vue3中使用swiper7轮播图插件
【华为云开发者联盟】Vue3.x使用Swiper Vue插件最新详细教程(包含修改swiper样式)