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 HTMLElement
speed. value = 1 ;
timer. value = window. requestAnimationFrame ( function fn ( ) {
if ( speed. value < 90 ) {
speed. value += 1
dom. style. width = speed. value+ '%' ;
timer. value = window. requestAnimationFrame ( fn)
} else {
speed. value = 1 ;
window. cancelAnimationFrame ( timer. value)
}
} )
}
const endLoading = ( ) => {
let dom = bar. value as HTMLElement
setTimeout ( ( ) => {
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>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
新建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 { 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' )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33