事情是这也的,有天遇到一个需要比较复杂滑动的效果,于是乎自然自然想到我们前端手扶拖拉机手的老朋友swiper,此时靓仔如我,已经是用上了vue3+ts+vite的爽歪歪组合,想来这swiper也是个高端的稀罕物件儿,果然让我找到了最新版,官方基于vue3做了组件与hook的封装,对ts有了更好的支持。然鹅.....就在我以为一切尽在掌握,却发现有点味儿不!
习惯了之前的模式,组件化的调整拆分了所有的模块,需要单独引用modules[]之后,在props上传入之前实例化的参数,稍稍试了一下,大概摸清楚了新版的使用模式如下。
新版网站: www.swiper.com.cn/
经典版网站:swiperjs.com/vue
<template>
<div id="home">
<!-- direction="vertical" -->
<!-- props的配置跟原来版本实例化时候的配置一样,只是转换格式即可 -->
<swiper
@swiper="onSwiper"
@slideChange="onSlideChange"
:modules="modules"
:keyboard="true"
:mousewheel="true"
:navigation="{nextEl: '.swiper-button-next',prevEl: '.swiper-button-prev'}"
:pagination="{el:'.pagination',type: 'bullets'}"
:scrollbar="{el: '.swiper-scrollbar',draggable: true}"
direction="vertical"
>
<swiper-slide :class="`item${index}`" v-for="(item,index) in [1,2,3,4]" :key="index">Slide {{item}}</swiper-slide>
</swiper>
<button class="swiper-button-next">next</button>
<button class="swiper-button-prev">prev</button>
<div class="pagination"></div>
<div class="swiper-scrollbar"></div>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
//这里拆分了模块,按需引入,注意一些模块需要引入css才能生效
import { Navigation, Pagination, Scrollbar, A11y, Keyboard, Mousewheel } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/vue';
import SwiperType from 'swiper/types';//引入类型文件
import 'swiper/css';
import 'swiper/scss/pagination';
import 'swiper/scss/scrollbar';
export default defineComponent({
setup() {
const state = reactive({
});
const onSwiper = (swiper:SwiperType.Swiper) => {
console.log(swiper);
};
const onSlideChange = () => {
console.log('slide change');
};
return {
onSwiper,
onSlideChange,
modules: [Navigation, Keyboard, Mousewheel, Pagination, Scrollbar],
...toRefs(state),
};
}, //setup
components: {
Swiper,
SwiperSlide
},
});
</script>
<style lang="scss" scoped>
@import "@/styles/variable.scss";
#home {
.swiper {
height: 100vh;
}
.swiper-slide{
height: 90vh;
border: 1px solid red;
&.item1{
background: red;
}
&.item0{
background: gold;
}
&.item3{
background: green;
}
}
.swiper-scrollbar{
height: 10px;
}
}
</style>