Vue2 使用 vue-awesome-swiper swiper
· 阅读需 7 分钟
最近用 Vant@2 中的 Swipe
时候,发现 iPhone 手机轮播动画可能丢失。但是有的项目升级 Vant@2 的小版本后,解决了。也有的项目,用最新版也不能解决。同时发现它的计算宽度有时候在 iPhone 下还有问题。这也使得必须考虑切换为标准版 swiper
了。
说明
Vue@2 项目,可以直接使用 swiper
的 js 版本,不过接入起来比较麻烦,尤其是控制各种事件,很少有人这么做了。
最常见就是使用 vue-awesome-swiper
。目前主要是用 4.1.1 版本,也有人用 3.1.3 版本。最新的 5.0.1 应该是为了兼容比较新版本的 Swiper,且不会继续维护了,使用人数也非常少。
其中:
- 4.1.1 要配合
swiper
的 5/6 版本来用。 - 3.1.3 要配合
swiper
的 4 版本来用。
下文以 vue-awesome-swiper
4.1.1 来进行说明。
实践
安装依赖
首先是项目安装依赖:
npm i vue-awesome-swiper@4.1.1
npm i swiper@6.8.4
# 或者安装 Swiper@5 系列版本,但代码略有不同,下文会说明
npm i swiper@5.4.5
这一步不难,不过如果你用 npm
的话,可能会安装失败,可以尝试增加参数:
npm i swiper@6.8.4 --legacy-peer-deps
模版代码
模版部分参考代码如下:
<template>
<div class="container">
<Swiper
:options="swiperOption"
ref="mySwiper"
@clickSlide="onSlideClick"
@slideChange="onSlideChange">
<SwiperSlide v-for="item in list" :key="item.id">
<div class="item" :style="{backgroundColor:item.bg}">
{{ item.text }}
</div>
</SwiperSlide>
<!-- swiper 自带指示器 -->
<template #pagination>
<div class="swiper-pagination"/>
</template>
</Swiper>
<!-- 自定义指示器 -->
<div class="pagination">
<span
v-for="idx in list.length"
:key="idx"
:class="{cur:(idx-1)===curIndex}"/>
</div>
</div>
</template>
<style lang="less" scoped>
.container {
.item {
height: 100px;
}
/* 简易的指示器效果 */
.pagination {
display: flex;
span {
margin: 0 2px;
width: 10px;
height: 10px;
background-color: grey;
&.cur {
background-color: red;
}
}
}
}
</style>
指示器,可以使用自带的,也可以自己写一个完全定义的。看你的需求来定。
这部分没什么可说的。具体的调用方法,下文部分会提到。