最近在学习 vue3 + ts 想实现一个如下图swiper轮播图的效果
看似非常简单,结果还是遇到不少坑,就此写下来,方便以后自己回看,也望能够助力秃友们~
首先咱们得先安装swiper组件
npm i swiper // 安装太慢的话,npm淘宝镜像 npm config set registry https://registry.npm.taobao.org
界面的话
<script setup lang="ts">
import { ref } from 'vue'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
const useSwiper = ref(null)
const activeTab = ref(0) // tabs 索引
const swiperOption = {
spaceBetween: 0,
slidesPerView: 1, // 一屏显示的slide个数 'auto'
slidesPerGroup: 1, // 每组多少个swiper滑块
scrollbar: { draggable: true },
grabCursor: true, // 抓手光标 很关键
navigation: true, // 1默认,在内
loop: true, // 循环 很关键
}
function onSwiper(swiper) {
// 刷新页面触发 swiper实例化 赋值到变量
useSwiper.value = swiper
}
function onSlideChange(Swiper) {
// 赋值到你的tabs标题
activeTab.value = Swiper.realIndex
}
// 设置点击标题,跳转到对应的轮播图 假设是getTabs
function getTabs(id: number) {
activeTab.value = id
useSwiper.value?.slideToLoop(id) // 这个属性很关键 slideToLoop,不能是 slideTo 不然光标往左移动的时候,点击标题,标题索引会错乱
}
</script>
// 页面就按照自己需要来,官方为例子
<template>
<swiper
v-bind="swiperOption"
@swiper="onSwiper"
@slideChange="onSlideChange"
>
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide>
<swiper-slide>Slide 3</swiper-slide>
...
</swiper>
</template>
后续如果有问题!在进行补充~