vue3定时器 每隔10秒请求一次接口
<script lang="ts" setup>// 引入swiper组件
import { Swiper, SwiperSlide } from "swiper/vue";
import { ref,onUnmounted } from "vue";
import { getCompanyNameList } from "@/api/auth";
import { ElMessage,ElLoading } from "element-plus";
const listData = ref([]);
const timer = ref(); // 定时器
let count = ref(0); // 倒计时
const getDetailsList = async () => {
const loading = ElLoading.service({
lock: true,
text: 'Loading',
background: 'rgba(0, 0, 0, 0.7)',
})
const { data } = await getCompanyNameList();
if (data.length > 0) {
data.forEach((element: { bgColor: string }, i: number) => {
element.bgColor = bgColor.value[i];
});
listData.value = data;
count.value = 10;//成功时设置count.value = 10;并调用Verification 新一轮的倒计时
loading.close()
Verification();
} else {
ElMessage({
message: "暂无数据",
type: "warning",
});
}
};
//循环请求接口
const Verification = () => {
timer.value = setInterval(() => {
if (count.value > 0 && count.value <= 10) {
// loading.value = false
count.value--;
} else if (count.value === 0) {
getDetailsList();// 请求数据
clearInterval(timer.value);
timer.value = null;
}
}, 1000);
};
onUnmounted(()=>{
clearInterval(timer.value);
timer.value = null;
})
</script>