1.需求:
1.1:有一个长度不限的数组中存放着想要展示的元素,展示篇幅只能放下四个元素
1.2:通过左右按钮实现按数组次序左右移动
1.3:数组长度小于4时,隐藏左右按钮
1.4:数组长度大于四,展示数组处于刚开头,不能再向前移动,处于最后时不能再向后移动
2.代码实现:
<template>
<div class="testBtnConral">
<el-button
type="primary"
:icon="buttons.dArrowLeft"
class="dArrowLeft"
@click="selectLeftImg"
:class="{ asFormer: Datas.toLeft }"
></el-button>
<span v-for="(item, index) in Datas.beInterceptedArr" :key="index">{{ item }}</span>
<el-button
type="primary"
:icon="buttons.dArrowRight"
class="dArrowRight"
@click="selectRightImg"
:class="{ asLast: Datas.toRight }"
></el-button>
</div>
</template>
<script lang="ts" setup>
import ImageUploader from '@/components/ImageUploader/index.vue'
import { buttons } from '@/components/button'
import { ref, reactive } from 'vue'
let Datas = reactive({
//向右按钮显隐
toLeft: true,
//向左按钮显隐
toRight: false,
//被截取元素的暂存数组
beInterceptedArr: []
})
//原数组
var contraledSpans = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff']
//先加载一组
Datas.beInterceptedArr = contraledSpans.slice(0, 4)
function a() {
//原数组长度不大于4不显示向右按钮
if (contraledSpans.length <= 4) {
Datas.toRight = true
}
}
a()
//点击向右按钮
function selectRightImg() {
//找到上一组数组的第一个元素在原数组的位置
var index = contraledSpans.map((item) => item).indexOf(Datas.beInterceptedArr[0])
//判断最后一组只剩三个元素则不再继续切割
if (index + 4 <= contraledSpans.length) {
//根据上述位置往后挪一个存入截取数组
Datas.beInterceptedArr = contraledSpans.slice(index + 1, index + 5)
//到最后只有三个元素的元素组时,关闭往右按钮
if (Datas.beInterceptedArr.length === 3) {
Datas.toRight = true
}
//没有到开头位置,打开向左按钮
if (Datas.beInterceptedArr[0] !== contraledSpans[0]) {
Datas.toLeft = false
}
}
}
// 点击向左按钮
function selectLeftImg() {
// 找到上面向右操作后暂存数组中第一个元素,到元数组中去匹配,找到此元素下标
var index = contraledSpans.map((item) => item).indexOf(Datas.beInterceptedArr[0])
if (index >= 1) {
//得到下标后往前移一个下标,此下标则是暂存数组中第一个元素
Datas.beInterceptedArr = contraledSpans.slice(index - 1, index + 3)
//没有到最后只有三个元素的元素组时,打开往右按钮
if (Datas.beInterceptedArr.length == 4) {
Datas.toRight = false
}
}
//到开头位置,关闭向左按钮
if (Datas.beInterceptedArr[0] === contraledSpans[0]) {
Datas.toLeft = true
}
}
</script>
<style lang="scss" scoped>
.testBtnConral {
display: flex;
width: 320px;
align-items: center;
.dArrowLeft {
margin-right: 10px;
background-color: #fff;
color: #000;
border: 0;
font-size: 20px;
}
.asFormer {
color: #fff;
}
.asLast {
color: #fff !important;
}
span {
width: 40px;
height: 100%;
background-color: gray;
margin: 5px;
}
.dArrowRight {
margin-left: auto;
margin-right: 10px;
background-color: #fff;
color: #000;
border: 0;
font-size: 20px;
}
}
</style>
3.具体实现: