在Vue中推荐一款做轮播图的插件 – Swiper
文章目录
首先上效果:
一:如何使用
1.下载依赖
npm install swiper vue-awesome-swiper --save
# or
yarn add swiper vue-awesome-swiper
2.在main.js中全局引用加载
import VueAwesomeSwiper from 'vue-awesome-swiper'
// import style
import 'swiper/css/swiper.css'
// If you use Swiper 6.0.0 or higher
import 'swiper/swiper-bundle.css'
Vue.use(VueAwesomeSwiper, /* { default options with global component } */)
3.使用(注意看下自己Swaper的版本,6.X以上版本引用css文件方式不一样)
import { Swiper, SwiperSlide, directive } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
// If you use Swiper 6.0.0 or higher
import 'swiper/swiper-bundle.css'
export default {
components: {
Swiper,
SwiperSlide
},
directives: {
swiper: directive
}
}
4. 示例代码
js代码:
<script>
import { Swiper, SwiperSlide, directive } from 'vue-awesome-swiper';
import 'swiper/css/swiper.css';
export default {
name: 'PageControl',
components: {
Swiper,
SwiperSlide,
},
directives: {
swiper: directive,
},
data() {
return {
pageMenus: hnConfig.app.system.pageControl.pageMenus.pageMenu,
swiperOption: {
//可视区域展示多少个滑块
slidesPerView: 5,
//每个滑块的margin-left 这里是20px
spaceBetween: 20,
freeMode: true,
//是否开始循环模式
loop: true,
//配置前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
//这里可以配置点击事件
on: {
click: function () {
},
},
},
};
},
methods: {
itemClick(item) {
this.$router.push({
name: item.component,
params: {
title: item.name,
},
});
},
},
};
</script>
HTML代码:切记,如果要加上前进后退按钮,请加上这两个div,代码中有
<template>
<Row class="pageControl">
<div class="pageControl-content">
<div class="pageControl-content-wrapper">
<swiper
v-if="pageMenus.length>0"
:options="swiperOption"
>
<swiper-slide
v-for="(item,index) in pageMenus"
:key="index"
class="content-item"
>
<div @click="itemClick(item)">
<img :src="`./static/images/hn/${item.icon}.png`" />
<div class="item-name">{{ item.name }}</div>
</div>
</swiper-slide>
</swiper>
</div>
<!-- 如果需要导航按钮 -->
<div class="swiper-button-prev swiper-button-white"></div>
<div class="swiper-button-next swiper-button-white"></div>
</div>
</Row>
</template>
CSS:
<style lang="less" scoped>
.pageControl-content {
width: 100%;
height: calc(~'(100% - 500px)');
margin: 250px 0 250px 0;
.pageControl-content-wrapper {
width: calc(~'(100% - 400px)');
height: 100%;
margin: 0 200px 0 200px;
.content-item {
width: 20%-20px;
height: 390px;
float: left;
text-align: center;
padding: 90px 0 0 0;
background: rgba(255, 255, 255, 0.4);
cursor: pointer;
.item-name {
font-size: 18px;
color: #222328;
font-weight: 400;
margin: 31px 0 38px 0;
}
.item-description {
font-size: 16px;
color: #3a3d4b;
}
}
}
}
</style>
二:可能出现的问题
1. 给每个滑块绑定的click点击方法不生效
在这里就不细纠原因,我的解决方法是不在swiper-slide中写@click,而是在包裹滑块中内容的div中添加@click。具体代码上面有。
三:官方参考
- 具体使用方法请参考: Swiper组件使用教程(第一步)
- API 文档地址入口:请戳这里进入(第二步)
- 官网地址:https://www.swiper.com.cn/