前端进度条-mock 版
效果演示
效果实现
1.创建 ProgressBar
组件
创建一个名为 ProgressBar.vue
的组件,用于显示下载进度。
vue
<script setup>
import { ref, onMounted } from "vue";
const timer = ref(null);
const init = () => {
const DATA = {
progess: 0, // 当前资源的下载进度
resourceNo: 1, // 下载的资源编号
resourceTotal: 3, // 需下载的资源总数
};
clearInterval(timer.value);
timer.value = setInterval(() => {
DATA.progess++;
if (DATA.progess > 100) {
DATA.progess = 0;
DATA.resourceNo++;
if (DATA.resourceNo > DATA.resourceTotal) {
clearInterval(timer.value);
window.$bus.emit("spin", "资源解析中, 请稍后...");
return;
}
}
window.$bus.emit(
"spin",
`资源加载中(${DATA.resourceNo}/${DATA.resourceTotal}) ${DATA.progess}%`
);
}, 333); // 模拟下载进度, 每秒 333ms 增加进度
};
const cancel = () => {
clearInterval(timer.value);
window.$bus.emit("spin", false);
};
onMounted(() => {
window.$bus.off("progressbar");
window.$bus.on("progressbar", (param) => {
switch (param) {
case "start":
init();
break;
case "cancel":
cancel();
break;
default:
init();
}
});
});
</script>
2.引用 ProgressBar
组件
在 App 组件中,使用 ProgressBar
组件来显示下载进度。
vue
<script setup>
import ProgressBar from "@/components/ProgressBar.vue";
</script>
<template>
<ProgressBar></ProgressBar>
</template>
3.在组件中使用
vue
<script setup>
const mockDownSth = () => new Promise((resolve) => setTimeout(resolve, 10000));
const doDownload = () => {
window.$bus.emit("progressbar", "start");
mockDownSth().finally(() => {
clearInterval(this.timer);
this.$bus.emit("spin", "资源加载完毕, 请稍后...");
setTimeout(() => {
this.$bus.emit("spin", false);
}, 1000);
});
};
const doCancel = () => window.$bus.emit("progressbar", "cancel");
</script>
<template>
<el-button type="primary" @click="doDownload()">下载资源</el-button>
<el-button
type="danger"
@click="doCancel()"
style="position: relative;z-index: 100;"
>取消下载</el-button
>
</template>