通过设置一个rotationOrder数组控制选中顺序,然后设置一个定时器重复循环这个数组
<template>
<button @click="start">开始抽奖</button>
<button @click="stop">停止</button>
// 我使用的是unocss,这里更改为自己的样式就好
<view class="flex w-360px justify-around flex-wrap">
<view
v-for="(item, index) in data"
:key="item.id"
class="w-100px h-100px rd-8px flex-xy-center b-1 b-solid-#ccc"
:class="{ active: activeIndex === index }"
>
{{ item.name }}</view
>
</view>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
let activeIndex = ref(0);
const data = ref([
{ name: "一等奖", id: 1 },
{ name: "谢谢参与", id: 2 },
{ name: "二等奖", id: 3 },
{ name: "一等奖", id: 4 },
{ name: "谢谢参与", id: 5 },
{ name: "二等奖", id: 6 },
]);
// 控制选中顺序
const rotationOrder = [1, 2, 5, 4, 3];
let rotationIndex = 0;
let stopIndex: number | undefined = undefined;
// eslint-disable-next-line no-undef
let timer: NodeJS.Timeout;
function start() {
timer = setInterval(() => {
if (data.value.length > 0) {
if (rotationIndex < rotationOrder.length) {
activeIndex.value = rotationOrder[rotationIndex++];
} else {
activeIndex.value = 0;
rotationIndex = 0;
}
} else {
console.error("所有奖项已全部抽完");
}
}, 50);
}
function stop() {
clearInterval(timer);
}
watch(activeIndex, (newValue) => {
if (newValue === stopIndex) {
stop();
}
});
// 模拟通过后端请求获取具体抽中的奖品
setTimeout(() => {
stopIndex = 2;
}, 3000);
</script>
<style scoped>
.active {
background-color: orange;
}
</style>