这是一个简单的 Vue.js 测试应用程序,代码如下所示:
<template>
<div>
<button @click="onPrevious">Previous</button>
<button @click="onNext">Next</button>
<br><br>
<div v-for="(a, index) in chunkedArr()" :key="index">
<div v-for="(i, index) in a" :key="index">{{ i }}</div>
-
</div>
</div>
</template>
<script>
export default {
data() {
return {
input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
newInput: [],
currentIndex: 0
}
},
mounted() {
const temp = []
for (let i = 0; i < this.input.length; i += 3) {
let chunk = this.input.slice(i, i + 3)
if (chunk.length === 1) {
chunk = chunk.concat(this.input.slice(0, 2))
}
if (chunk.length === 2) {
chunk = chunk.concat(this.input.slice(0, 1))
}
temp.push(chunk)
}
this.newInput = temp.flat()
},
methods: {
chunkedArr() {
if (this.newInput.length === 0) {
return
}
const output = []
for (let i = this.currentIndex; i < this.newInput.length; i += 3) {
let chunk = this.newInput.slice(i, i + 3)
output.push(chunk)
}
console.log(output)
return output
},
onNext () {
this.chunkedArr()
},
onPrevious () {
// TODO
}
},
}
</script>
我们可以使用 Next 和 Previous 按钮模拟轮播。假设我们有一些应该在轮播中显示的元素数组。
但是,在这个轮播中,我们应该一次显示 3 个元素。这意味着只有在每次单击 Next/Previous 时才能看到 3 个元素。例如,如果我们有一个元素数组:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,初始状态是显示:1, 2, 3。首先点击接下来,轮播应显示 4、5、6 等。数组末尾有 3 种情况。数组的末尾可以有 1、2 或 3 个元素。如果它有 3 个元素,一切都很简单。但是如果它有1个或2个元素,我们需要分别添加2个或1个元素。如果最后有 1 个元素,我们需要添加数组的前 2 个元素以显示 3 个元素。如果最后有 2 个元素(我们的测试用例),我们只需要添加第一个元素以显示 3 个元素。根据先前描述的情况,轮换应该更进一步。
请看一下所附的屏幕截图:
在实际情况下,我需要 BootstrapVue 的 Carousel 的数据结构。
更新:
输出数组中有 4 个子数组。请看下面的截图:
更新:
const example = [1, 2, 3, 4, 5];
const subArrayIterator = subArrayGenerator(example);
console.log('init: ' + subArrayIterator.next().value); // init
const prevBtn = document.getElementById('prev');
const nextBtn = document.getElementById('next');
prevBtn.onclick = () => {
console.log(subArrayIterator.next(false).value);
}
nextBtn.onclick = () => {
console.log(subArrayIterator.next().value);
}
function* subArrayGenerator(inputArray, subArrayLength=3) {
let prev = false;
for (let i = 0; i < inputArray.length;) {
if (prev) {
let diff = subArrayLength*2;
if (diff > inputArray.length) {
diff = diff % inputArray.length;
}
diff = i - diff;
i = diff < 0 ? inputArray.length + diff : diff;
}
const subArray = [];
for (let j = 0; j < subArrayLength; j++) {
subArray.push(inputArray[i]);
i = i < inputArray.length - 1 ? i + 1 : 0;
}
prev = (yield subArray) === false;
}
}
<button type="button" id="prev">prev</button>
<button type="button" id="next">next</button>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句