首先
在head中引入swiper的css和js
javascript
<link rel="stylesheet" href="./static/css/swiper-bundle.min.css">
<script src="./static/js/swiper-bundle.min.js"></script>
下载地址
https://www.swiper.com.cn/download/index.html#file1
代码
主要看swiper结构,自定义按钮样式放在swiper盒子外面,然后再用css隐藏它本来的箭头样式,一定要记住在按钮最外层包一个大盒子class为next-box设置相对定位。这样自定义的按钮才会出现,不然就会出不来。
html
javascript
<div class="carousel-container">
<div class="swiper">
<div class="swiper-wrapper" v-if="noticeList2.length > 0">
<div class="swiper-slide" v-for="(item,index) in noticeList2" :key="index">
<div v-for="(item2,index2) in item" :key="index2">
<div class="single-blog">
<div class="blog-img img-full">
<a :href="'detail.html?noticeId='+item2.noticeId" :title="item2.noticeName">
<img style="width: 100%;height: 240px;" :src="item2.noticeImage" alt="">
</a>
</div>
<div class="blog-content">
<h3 class="post-title text-ellipsis-1"><a :href="'detail.html?noticeId='+item2.noticeId" :title="item2.noticeName">{{item2.noticeName||''}}</a></h3>
<p class="post-description text-ellipsis-2">{{item2.noticeDesc||''}}</p>
<div class="d-flex justify-content-between">
<div class="text-muted">{{defaultType(item2.defaultType)}}相关</div>
<div class="text-muted">{{parseTime(item2.createTime*1000,'{y}-{m}-{d}')}}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
//左右切换按钮
<div class="next-box">
<div class="swiper-button-prev">
<el-button circle size="large">
<i class="fa fa-arrow-left"></i>
</el-button>
</div>
<div class="swiper-button-next">
<el-button type="danger" circle size="large">
<i class="fa fa-arrow-right "></i>
<!-- <i class="fa-regular fa-angle-right"></i> -->
</el-button>
</div>
</div>
</div>
JS 这是数组转换方法
javascript
let objArray = [{a: 1}, {b: 2}, {c: 3}, {d: 4}, {e: 5}, {f: 6}, {g: 7}];
let len = objArray.length;
let n = 3; //假设每行显示3个
let lineNum = len % 3 === 0 ? len / 3 : Math.floor( (len / 3) + 1 );
let res = [];
for (let i = 0; i < lineNum; i++) {
let temp = objArray.slice(i*n, i*n+n);
res.push(JSON.parse(JSON.stringify(temp)));
}
console.log(res);
this.noticeList2 = result
javascript
<script>
window.onload = function() {
var mySwiper = new Swiper('.swiper', {
// direction: 'vertical', // 垂直切换选项
loop: false, // 循环模式选项
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
// slidesPerView: 'auto',
// loopedSlides: 3,
})
$('.next-box').click(function(){
document.getElementById('realIndex').innerHTML = '0' + Number(mySwiper.realIndex + 1)
})
}
</script>
CSS
javascript
.swiper {
width: 100%;
}
.next-box {
position: relative;
}
.swiper-button-next:after, .swiper-button-prev:after {
display: none;
}
.swiper-button-next, .swiper-button-prev {
position: initial !important;
margin: 0 !important;
}
.swiper-slide {
display: flex;
}
实现效果
就是一行展示三列数据,每次切换一次, 展示一个。
注意: 点击按钮或者分页出现黑色边框
javascript
.swiper-pagination-bullet-active:focus {
outline: none;
}