前端vue路由跳转的中转页怎么写
时间: 2024-03-21 09:41:49 浏览: 22
在Vue中,可以使用路由组件来实现前端路由跳转的中转页,以下是一个简单的示例:
1. 创建一个名为`Loading.vue`的中转页组件,如下所示:
```vue
<template>
<div>
<p>Loading...</p>
</div>
</template>
<script>
export default {
name: 'Loading'
}
</script>
```
2. 在路由配置中,将中转页组件与目标组件进行关联,如下所示:
```js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home.vue'
import Loading from '@/components/Loading.vue'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('@/views/About.vue'),
beforeEnter: (to, from, next) => {
// 在进入目标路由前展示中转页
router.app.$root.showLoading = true
next()
}
}
]
})
// 在全局中定义showLoading变量,用于控制是否展示Loading组件
Vue.mixin({
data() {
return {
showLoading: false
}
}
})
router.beforeEach((to, from, next) => {
// 在路由跳转前,将showLoading设置为false,确保Loading组件不会一直显示
router.app.$root.showLoading = false
next()
})
router.afterEach((to, from) => {
// 在路由跳转后,将showLoading设置为false,确保Loading组件不会一直显示
router.app.$root.showLoading = false
})
export default router
```
在上述代码中,我们在路由配置中的`About`路由上使用了`beforeEnter`函数,当用户进入该路由时,先展示`Loading`组件,等待目标组件加载完成后再进行跳转。同时,在全局中定义了一个`showLoading`变量,用于控制是否展示`Loading`组件。
需要注意的是,在每次路由跳转前和跳转后,都要将`showLoading`变量设置为`false`,以确保`Loading`组件不会一直显示。