为了实现页面加载时的进度条功能,我们可以利用vue-router路由导航守卫的特性,监听路由跳转前后的事件,来实现页面加载状态的追踪和展示。下面是具体实现的步骤:
1.在项目中安装nprogress插件
npm install --save nprogress
2.在路由配置文件中引入nprogress
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
- 在路由跳转前和跳转后分别添加nprogress的开始、结束事件
router.beforeEach((to, from, next) => {
Nprogress.start()
next()
})
router.afterEach(() => {
Nprogress.done()
})
- 在页面模板中添加nprogress的进度条元素
<!-- App.vue -->
<template>
<div id="app">
<router-view />
<Nprogress :is-show="show"/>
</div>
</template>
- 在Nprogress.vue组件中实现进度条的展示和隐藏
<!-- Nprogress.vue -->
<template>
<div class="nprogress-container" :class="{show: isShow}">
<div class="nprogress-bar"></div>
</div>
</template>
<script>
export default {
props: {
isShow: {
type: Boolean,
default: false
}
}
}
</script>
<style>
.nprogress-container {
position: fixed;
top: 0;
left: 0;
height: 2px;
width: 100%;
background-color: #e0e0e0;
z-index: 9999;
transition: opacity .2s linear;
opacity: 0;
}
.nprogress-container.show {
opacity: 1;
}
.nprogress-bar {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 0;
background-color: #2196f3;
transition: width .1s ease-out;
}
</style>
完成以上步骤,我们就成功实现了vue页面加载时的进度条功能。nprogress插件提供了多种主题和样式配置,大家可以上官网查看文档进行自定义设置。
这里再举两个示例说明一下:
示例一:引入进度条组件但不在所有路由跳转前后都显示进度条
通过watch监听$route变化,当路由跳转时动态控制进度条的显示和隐藏。
<!-- App.vue -->
<template>
<div id="app">
<Nprogress :is-show="show"/>
<transition name="fade">
<router-view />
</transition>
</div>
</template>
<script>
import Nprogress from '@/components/Nprogress.vue'
export default {
components: { Nprogress },
data() {
return {
show: false
}
},
watch: {
$route(to, from) {
if (to.path === '/login' || to.path === '/register') {
this.show = false
} else {
this.show = true
}
}
}
}
</script>
示例二:自定义进度条组件样式
<!-- Nprogress.vue -->
<template>
<div class="nprogress-container" :class="{show: isShow}">
<div class="nprogress-bar" :style="{background: barColor, height: barHeight}">
<div class="nprogress-peg"></div>
</div>
</div>
</template>
<script>
export default {
props: {
isShow: {
type: Boolean,
default: false
},
barColor: {
type: String,
default: '#29d',
},
barHeight: {
type: String,
default: '2px',
},
}
}
</script>
<style>
.nprogress-container {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
background-color: rgba(250, 250, 250, 0.8);
z-index: 9999;
display: flex;
justify-content: center;
align-items: center;
transition: opacity .2s linear;
opacity: 0;
}
.nprogress-container.show {
opacity: 1;
}
.nprogress-bar {
position: relative;
width: 80%;
height: 2px;
.nprogress-peg {
position: absolute;
right: 0px;
display: block;
width: 16px;
height: 100%;
border: none;
border-radius: 100px 0px 0px 100px / 4px 0px 0px 4px;
background-color: #fff;
box-shadow: 0 0 10px 1px #29d, 0 0 5px 0 #29d;
transform: rotate(3deg) translate(0px, -4px);
}
}
</style>
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:vue页面加载时的进度条功能(实例代码) - Python技术站