// 使用 TypeScript 时需要导入路由项目的类型声明
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/page/login/login.vue'
// 使用路由项目类型声明一个路由数组
const routes: Array<RouteRecordRaw> = [
{
path: '/',
component:Login,
},
{
path: '/tourist',
name:'tourist',
component: () => import('@/page/tourist/index.vue')
},
{
path: '/home',
name:'home',
component: () => import('@/page/index.vue'),
children:[
{
path: 'publicTable',
name: 'publicTable',
component: () => import('@/page/publicTable/index.vue'),
},
{
path:"publicOne",
name: 'publicOne',
component: () => import('@/page/pubicFiles/index.vue'),
},
{
path:"regulate",
name:"regulate",
component: () => import('@/page/systemUser/index.vue'),
},
]
},
{
path: '/:error*', // 路由通配,兜底路由
name: 'login',
component:Login,
}
]
const router = createRouter({
history:createWebHistory(),
routes
})
router.beforeEach((to, from, next) => {
// 在导航之前执行的逻辑,可以用来进行权限控制等
console.log('Before Each', to, from);
// 如果需要导航到下一个路由,调用 next(),否则调用 next(false) 或者传递一个路由对象 next({ path: '/login' })
next();
});
router.beforeResolve((to, from) => {
// 在导航被确认之前执行的逻辑
console.log('Before Resolve', to, from);
});
router.afterEach((to, from) => {
// 在导航之后执行的逻辑,比如记录页面浏览历史
console.log('After Each', to, from);
});
export default router;
这三个函数是 Vue Router 提供的全局导航守卫:
-
beforeEach(to, from, next):
- 在每次路由导航触发前调用。
- 参数
to
是即将要进入的路由对象,from
是当前导航正要离开的路由对象,next
是一个函数,调用它会继续执行导航过程。你可以在这个守卫中进行一些全局的导航前逻辑,如权限验证。
-
beforeResolve(to, from):
- 在导航被确认之前调用。
- 类似于
beforeEach
,但是在所有异步组件解析完之后被调用。可以在这里执行一些需要等到异步组件解析完后再进行的操作。
-
afterEach(to, from):
- 在每次路由导航完成后调用。
- 可以在这里执行一些全局的导航后逻辑,如记录用户行为、埋点等。
这些导航守卫允许你在路由导航的不同阶段添加一些自定义的逻辑。在 beforeEach
中,你可以阻止或者修改导航;在 beforeResolve
中,你可以等待异步组件解析完成;在 afterEach
中,你可以执行一些导航后的操作。