Vue3加载条(LoadingBar)

简介: 这是一个基于 Vue 的加载条组件,提供了丰富的自定义选项和方法。通过简单的 API,可以控制加载条的开始、结束及错误状态。支持设置容器类名、样式、颜色等属性,并可通过 `start`、`finish` 和 `error` 方法来触发不同状态。

效果如下图:在线预览

在这里插入图片描述

APIs

LoadingBar

参数 说明 类型 默认值
containerClass 加载条容器的类名 string undefined
containerStyle 加载条容器的样式 CSSProperties {}
loadingBarSize 加载条大小,单位 px number 2
colorLoading 加载中颜色 string ‘#1677ff’
colorFinish 加载完成颜色 string ‘#1677ff’
colorError 加载错误颜色 string ‘#ff4d4f’
to 加载条的挂载位置,可选:元素标签名(例如 body)或者元素本身 string | HTMLElement ‘body’

Methods

名称 说明 类型
start 开始加载的回调函数 (from = 0, to = 80) => void
finish 结束加载的回调函数 () => void
error 出现错误的回调函数 () => void

创建加载条组件LoadingBar.vue

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import type { CSSProperties } from 'vue'
interface Props {
  containerClass?: string // 加载条容器的类名
  containerStyle?: CSSProperties // 加载条容器的样式
  loadingBarSize?: number // 加载条大小,单位 px
  colorLoading?: string // 加载中颜色
  colorFinish?: string // 加载完成颜色
  colorError?: string // 加载错误颜色
  to?: string | HTMLElement // 加载条的挂载位置,可选:元素标签名(例如 body)或者元素本身
}
withDefaults(defineProps<Props>(), {
  containerClass: undefined,
  containerStyle: () => ({}),
  loadingBarSize: 2,
  colorLoading: '#1677ff',
  colorFinish: '#1677ff',
  colorError: '#ff4d4f',
  to: 'body'
})
const showLoadingBar = ref(false)
const loadingBarRef = ref() // 加载条 DOM 引用
const loadingStarted = ref(false) // 加载条是否开始
const loadingFinishing = ref(false) // 加载条是否完成
const loadingErroring = ref(false) // 加载条是否报错
async function init() {
  showLoadingBar.value = false
  loadingFinishing.value = false
  loadingErroring.value = false
}
async function start(from = 0, to = 80, status: 'starting' | 'error' = 'starting') {
  // 加载条开始加载的回调函数
  loadingStarted.value = true
  await init()
  if (loadingFinishing.value) {
    return
  }
  showLoadingBar.value = true
  await nextTick()
  if (!loadingBarRef.value) {
    return
  }
  loadingBarRef.value.style.transition = 'none' // 禁用过渡
  loadingBarRef.value.style.maxWidth = `${from}%`
  void loadingBarRef.value.offsetWidth // 触发浏览器回流(重排)
  loadingBarRef.value.className = `loading-bar loading-bar-${status}`
  loadingBarRef.value.style.transition = ''
  loadingBarRef.value.style.maxWidth = `${to}%`
}
async function finish() {
  // 加载条结束加载的回调函数
  if (loadingFinishing.value || loadingErroring.value) {
    return
  }
  if (loadingStarted.value) {
    await nextTick()
  }
  loadingFinishing.value = true
  if (!loadingBarRef.value) {
    return
  }
  loadingBarRef.value.className = 'loading-bar loading-bar-finishing'
  loadingBarRef.value.style.maxWidth = '100%'
  void loadingBarRef.value.offsetWidth // 触发浏览器回流(重排)
  showLoadingBar.value = false
}
function error() {
  // 加载条出现错误的回调函数
  if (loadingFinishing.value || loadingErroring.value) {
    return
  }
  if (!showLoadingBar.value) {
    void start(100, 100, 'error').then(() => {
      loadingErroring.value = true
    })
  } else {
    loadingErroring.value = true
    if (!loadingBarRef.value) {
      return
    }
    loadingBarRef.value.className = 'loading-bar loading-bar-error'
    loadingBarRef.value.style.maxWidth = '100%'
    void loadingBarRef.value.offsetWidth
    showLoadingBar.value = false
  }
}
function onAfterEnter() {
  if (loadingErroring.value) {
    showLoadingBar.value = false
  }
}
async function onAfterLeave() {
  await init()
}
defineExpose({
  start,
  finish,
  error
})
</script>
<template>
  <Teleport :disabled="!to" :to="to">
    <Transition name="fade-in" @after-enter="onAfterEnter" @after-leave="onAfterLeave">
      <div v-show="showLoadingBar" class="m-loading-bar-container" :class="containerClass" :style="containerStyle">
        <div
          ref="loadingBarRef"
          class="loading-bar"
          :style="`--loading-bar-size: ${loadingBarSize}px; --color-loading: ${colorLoading}; --color-finish: ${colorFinish}; --color-error: ${colorError}; max-width: 100%;`"
        ></div>
      </div>
    </Transition>
  </Teleport>
</template>
<style lang="less" scoped>
.fade-in-enter-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.fade-in-leave-active {
  transition: all 0.8s cubic-bezier(0.4, 0, 0.2, 1);
}
.fade-in-enter-from,
.fade-in-leave-to {
  opacity: 0;
}
.m-loading-bar-container {
  z-index: 9999;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: var(--loading-bar-size);
  .loading-bar {
    width: 100%;
    transition:
      max-width 4s linear,
      background 0.2s linear;
    height: var(--loading-bar-size);
    border-radius: var(--loading-bar-size);
  }
  .loading-bar-starting {
    background: var(--color-loading);
  }
  .loading-bar-finishing {
    background: var(--color-finish);
    transition:
      max-width 0.2s linear,
      background 0.2s linear;
  }
  .loading-bar-error {
    background: var(--color-error);
    transition:
      max-width 0.2s linear,
      background 0.2s linear;
  }
}
</style>

在要使用的页面引入

其中引入使用了以下组件:

<script setup lang="ts">
import LoadingBar from './LoadingBar.vue'
import { ref } from 'vue'
const loadingBar = ref()
const disabled = ref(true)
const localCardRef = ref()
const localLoadingBar = ref()
const customLoadingBar = ref()
function handleStart() {
  loadingBar.value.start()
  disabled.value = false
}
function handleFinish() {
  loadingBar.value.finish()
  disabled.value = true
}
function handleError() {
  disabled.value = true
  loadingBar.value.error()
}
</script>
<template>
  <div>
    <h1>{
  { $route.name }} {
  { $route.meta.title }}</h1>
    <h2 class="mt30 mb10">基本使用</h2>
    <Space>
      <Button type="primary" @click="handleStart">开始</Button>
      <Button :disabled="disabled" @click="handleFinish">结束</Button>
      <Button type="danger" @click="handleError">报个错</Button>
    </Space>
    <LoadingBar ref="loadingBar" />
    <h2 class="mt30 mb10">局部加载条</h2>
    <div class="m-container" ref="localCardRef">
      <Space>
        <Button type="primary" @click="localLoadingBar.start()">Start</Button>
        <Button @click="localLoadingBar.finish()">Finish</Button>
        <Button type="danger" @click="localLoadingBar.error()">Error</Button>
      </Space>
    </div>
    <LoadingBar ref="localLoadingBar" :container-style="{ position: 'absolute' }" :to="localCardRef" />
    <h2 class="mt30 mb10">自定义加载条样式</h2>
    <Space>
      <Button type="primary" @click="customLoadingBar.start()">Start</Button>
      <Button @click="customLoadingBar.finish()">Finish</Button>
      <Button type="danger" @click="customLoadingBar.error()">Error</Button>
    </Space>
    <LoadingBar
      ref="customLoadingBar"
      :loading-bar-size="5"
      color-loading="#2db7f5"
      color-finish="#52c41a"
      color-error="magenta"
    />
  </div>
</template>
<style lang="less" scoped>
.m-container {
  position: relative;
  display: flex;
  align-items: center;
  height: 200px;
  padding: 16px 24px;
  border: 1px solid #d9d9d9;
}
</style>
相关文章
|
6天前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
106 10
|
4月前
|
缓存 JavaScript PHP
斩获开发者口碑!SnowAdmin:基于 Vue3 的高颜值后台管理系统,3 步极速上手!
SnowAdmin 是一款基于 Vue3/TypeScript/Arco Design 的开源后台管理框架,以“清新优雅、开箱即用”为核心设计理念。提供角色权限精细化管理、多主题与暗黑模式切换、动态路由与页面缓存等功能,支持代码规范自动化校验及丰富组件库。通过模块化设计与前沿技术栈(Vite5/Pinia),显著提升开发效率,适合团队协作与长期维护。项目地址:[GitHub](https://github.com/WANG-Fan0912/SnowAdmin)。
735 5
|
1月前
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
249 1
|
1月前
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
145 0
|
2月前
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
95 0
|
4月前
|
JavaScript API 容器
Vue 3 中的 nextTick 使用详解与实战案例
Vue 3 中的 nextTick 使用详解与实战案例 在 Vue 3 的日常开发中,我们经常需要在数据变化后等待 DOM 更新完成再执行某些操作。此时,nextTick 就成了一个不可或缺的工具。本文将介绍 nextTick 的基本用法,并通过三个实战案例,展示它在表单验证、弹窗动画、自动聚焦等场景中的实际应用。
409 17
|
5月前
|
JavaScript 前端开发 算法
Vue 3 和 Vue 2 的区别及优点
Vue 3 和 Vue 2 的区别及优点
|
5月前
|
存储 JavaScript 前端开发
基于 ant-design-vue 和 Vue 3 封装的功能强大的表格组件
VTable 是一个基于 ant-design-vue 和 Vue 3 的多功能表格组件,支持列自定义、排序、本地化存储、行选择等功能。它继承了 Ant-Design-Vue Table 的所有特性并加以扩展,提供开箱即用的高性能体验。示例包括基础表格、可选择表格和自定义列渲染等。
412 6
|
4月前
|
JavaScript 前端开发 API
Vue 2 与 Vue 3 的区别:深度对比与迁移指南
Vue.js 是一个用于构建用户界面的渐进式 JavaScript 框架,在过去的几年里,Vue 2 一直是前端开发中的重要工具。而 Vue 3 作为其升级版本,带来了许多显著的改进和新特性。在本文中,我们将深入比较 Vue 2 和 Vue 3 的主要区别,帮助开发者更好地理解这两个版本之间的变化,并提供迁移建议。 1. Vue 3 的新特性概述 Vue 3 引入了许多新特性,使得开发体验更加流畅、灵活。以下是 Vue 3 的一些关键改进: 1.1 Composition API Composition API 是 Vue 3 的核心新特性之一。它改变了 Vue 组件的代码结构,使得逻辑组
1500 0
|
6月前
|
JavaScript 前端开发 UED
vue2和vue3的响应式原理有何不同?
大家好,我是V哥。本文详细对比了Vue 2与Vue 3的响应式原理:Vue 2基于`Object.defineProperty()`,适合小型项目但存在性能瓶颈;Vue 3采用`Proxy`,大幅优化初始化、更新性能及内存占用,更高效稳定。此外,我建议前端开发者关注鸿蒙趋势,2025年将是国产化替代关键期,推荐《鸿蒙 HarmonyOS 开发之路》卷1助你入行。老项目用Vue 2?不妨升级到Vue 3,提升用户体验!关注V哥爱编程,全栈开发轻松上手。
438 2