在项目中有些数据需要轮播展示时,使用Carousel组件非常合适,可以在页面内挂载很多内容节点,平常组件的循环显示方向默认是往右边滑动,但是在循环数量为2时,循环显示方向就会呈现一左一右,对于部分强迫症客户来说体验感就不是很好,如下图
实现循环数量为2时,循环显示的方向依旧为向右(上下滚动的除外)的思路
首先获取要循环的数据的长度length,如果为2时,复制一次,使其成为长度length为4的数组,然后将Carousel组件的indicators(下标显示器)多复制的给隐藏(原本长度为2,现在为4,就隐藏第3个和第4个)
最终成品效果如下
完整代码如下,可直接复制使用
<template>
<!-- 解决carousel的数据只有两条时,循环的方向会一左一右 -->
<div :class="[{'twoBox':isTwo},{'elseBox':!isTwo}]">
<el-carousel class="carouselBox">
<el-carousel-item v-for="item in list" :key="item">
<h3 class="small">{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
isTwo: false,
}
},
methods: {
getList() {
//模拟后端返回接口
setTimeout(() => {
//数据返回值
let res = [1, 2]
//假如长度为2时
if (res.length === 2) {
this.isTwo = true
//将2条数据复制一份为4条数据
this.list = res.concat(res)
} else {
this.isTwo = false
//其他时候正常赋值
this.list = res
}
}, 200)
}
},
mounted() {
this.getList()
}
}
</script>
<style lang="scss" scoped>
.twoBox {
width: 100%;
height: 100%;
.carouselBox {
width: 100%;
//将复制出来的数据的下标隐藏
:deep(.el-carousel__indicators) {
&>li:nth-child(3),
&>li:nth-child(4) {
display: none;
}
}
}
}
.elseBox {
width: 100%;
height: 100%;
.carouselBox {
width: 100%;
}
}
.el-carousel__item h3 {
color: gold;
font-size: 22px;
opacity: 0.75;
line-height: 150px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: blueviolet;
}
.el-carousel__item:nth-child(2n+1) {
background-color: green;
}
</style>