vue3中路由钩子
时间: 2023-06-28 21:07:55 浏览: 65
Vue3中的路由钩子函数和Vue2中基本相同,主要有以下几个:
1. beforeEach(to, from, next):在路由跳转之前执行,常用于用户登录验证。
2. afterEach(to, from):在路由跳转完成后执行,常用于页面访问统计。
3. beforeRouteEnter(to, from, next):在组件渲染前执行,常用于获取数据。
4. beforeRouteLeave(to, from, next):在组件离开前执行,常用于数据的保存或清理。
这些钩子函数可以通过在创建路由对象时进行配置,例如:
```
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
component: Home
},
{
path: '/about',
component: About,
beforeEnter: (to, from, next) => {
// 检查用户是否登录
if (!isAuthenticated()) {
next('/login')
} else {
next()
}
}
}
]
})
```
在上面的代码中,我们通过`beforeEnter`钩子函数来检查用户是否登录,如果未登录则跳转到登录页面。需要注意的是,`beforeEnter`只会在该路由被访问时执行,而不会在父路由或全局钩子函数中执行。