前言
近期项目需求需要实现一屏多张文字卡片轮播的效果,最终借用vue-awesome-swiper这个插件来实现,具体细节如下:
一、下载插件
考虑到新版本的兼容性问题,这里使用5.4.5的版本。
npm install swiper@5.4.5 vue-awesome-swiper --save
二、使用步骤
1.引入插件
import 'swiper/css/swiper.css'
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
2.注册组件
components: { Swiper, SwiperSlide }
3.引用组件
<!-- 频道导航 -->
<div class="channel-wrap" @mouseenter="swiper_enter" @mouseleave="swiper_leave">
<swiper ref="swiper" :options="options">
<swiper-slide class="channel-item" v-for="item in channelList" :key="item.id">
<div class="channel-icon">
<img class="icon-img" :src="item.releaseChannelIcon" alt="">
<img class="icon-img-check" :src="item.checkReleaseChannelIcon" alt="">
</div>
<div class="channel-title cp" @click="goSecondPage(item)">{{item.name}}</div>
<p class="column-title cp" v-for="column in item.columnBoList" :key="column.id"
@click="goSecondPage(item, column)">{{column.name}}</p>
</swiper-slide>
<!-- 添加分页器 -->
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</div>
4.data中添加swiper配置对象
options: {
// 频道轮播
pagination: {
el: '.swiper-pagination',
clickable: true // 分页可点击
},
loop: true, // 循环播放
loopedSlides: 6, //
slidesPerView: 6, // 页面显示的slides数量
speed: 1000, // 切换速度
autoplay: { // 自动播放
delay: 3000, // 每个slider单独停留的时间
stopOnLastSlide: false, // 切换到最后一个slide时不停止自动切换,loop环境下设置为true无效
disableOnInteraction: false // 用户操作swiper之后,不禁止autoplay
},
}
5.获取组件实例
// 引入组件
computed: {
swiper () {
return this.$refs.swiper.$swiper
}
},
// 设置悬停
swiper_enter () {
// 鼠标进入停止轮播
this.swiper.autoplay.stop()
},
swiper_leave () {
// 鼠标移出开始轮播
this.swiper.autoplay.start()
},
6.更改分页器样式
项目中是使用的less,直接更改分页器样式是不生效的,可以在style下方再加一个style,这样就可以直接更改分页器样式了。
<style>
.swiper-pagination-bullet {
width: 40px;
height: 4px;
display: inline-block;
border-radius: 3px;
background-color: #fff;
opacity: 1;
}
.swiper-pagination-bullet-active {
width: 40px;
height: 4px;
border-radius: 3px;
display: inline-block;
background-color: #ff7e00;
}
</style>
总结
这个项目只用到了分页器,就做了相应改动,如果需要用到导航的可以参考swiper官网进行配置,前端小白,欢迎各位大佬随时指正。