Vue3页面增加进度条
- 新建进度条组件
- 新建bar.ts
- 导航守卫中使用
Vue3项目使用导航守卫给页面增加进度条
新建进度条组件
loadingBar.vue
<template><div class="wraps"><div ref="bar" class="bar"></div></div>
</template><script setup lang=ts>
import { domainToASCII } from 'url';
import {onMounted, ref} from 'vue'let speed = ref<number>(1)
let bar = ref<HTMLElement>();
let timer = ref<number>(0);
const startLoading = () => {let dom = bar.value as HTMLElementspeed.value = 1;timer.value = window.requestAnimationFrame(function fn(){if(speed.value < 90){speed.value += 1dom.style.width = speed.value+'%';timer.value = window.requestAnimationFrame(fn)}else{speed.value = 1;window.cancelAnimationFrame(timer.value)}})
}const endLoading = ()=>{let dom = bar.value as HTMLElementsetTimeout(() => {window.requestAnimationFrame(()=>{speed.value = 100;dom.style.width = speed.value+"%"})}, 1000);
}
//暴露方法
defineExpose({startLoading,endLoading
})
</script><style scoped lang="less">
.wraps{position: fixed;top:0;width: 100%;height: 2px;.bar{height: inherit;width: 0;background: #1abcdc;}
}
</style>
新建bar.ts
import loadingBarVue from "./components/loadingBar.vue";
import { createVNode,render } from "vue";
const bar = createVNode(loadingBarVue);
render(bar,document.body)
export default bar
导航守卫中使用
main.ts
//import './assets/main.css'import { createApp,createVNode,render } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import bar from './bar'const app = createApp(App)
app.use(ElementPlus)
app.use(createPinia())
app.use(router)const whileList = ['/']router.beforeEach((to,from,next)=>{bar.component?.exposed?.startLoading()if(whileList.includes(to.path) || localStorage.getItem('token')){next()}else{next('/')}})router.afterEach((to,from)=>{bar.component?.exposed?.endLoading()
})app.mount('#app')