vue路由加载页面

当vue路由切换时,有时候会出现短暂白屏,需要添加一个加载状态

参考:buildadmin 地址:https://demo.buildadmin.com/#/

利用vue的路由导航守卫:beforeEachafterEach来判断显示加载状态的时间,当路由进入beforeEach开始显示加载页面,当路由进入afterEach结束加载状态

路由守卫

import { loading } from '@/utils/loading'

router.beforeEach((to, from, next) => {
   // 页面加载
  if (!(window as any).existLoading) {
    loading.show();
    (window as any).existLoading = true
  }
})

router.afterEach(() => {
  if ((window as any).existLoading) {
      loading.hide()
  }
})

加载组件 loading.ts

import { nextTick } from 'vue'
import '@/styles/loading.scss'

export const loading = {
    show: () => {
        const bodys: Element = document.body
        const div = document.createElement('div')
        div.className = 'block-loading'
        div.innerHTML = `
            <div class="block-loading-box">
                <div class="block-loading-box-warp">
                    <div class="block-loading-box-item"></div>
                    <div class="block-loading-box-item"></div>
                    <div class="block-loading-box-item"></div>
                    <div class="block-loading-box-item"></div>
                    <div class="block-loading-box-item"></div>
                    <div class="block-loading-box-item"></div>
                    <div class="block-loading-box-item"></div>
                    <div class="block-loading-box-item"></div>
                    <div class="block-loading-box-item"></div>
                </div>
            </div>
        `
        bodys.insertBefore(div, bodys.childNodes[0])
    },
    hide: () => {
        nextTick(() => {
            setTimeout(() => {
                const el = document.querySelector('.block-loading')
                el && el.parentNode?.removeChild(el)
            }, 200)
        })
    },
}
posted @ 2022-10-08 17:08  梦羽微澜  阅读(223)  评论(0编辑  收藏  举报