vue3路由白名单示例
时间: 2024-05-24 08:09:17 浏览: 293
Vue3提供了一个非常好用的路由插件Vue Router,其中包括了路由白名单的实现方式。
下面是一个简单的路由白名单的示例:
```javascript
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: Home,
meta: {
requiresAuth: true // 添加一个自定义字段,标记该路由需要登录才能访问
}
},
{
path: '/login',
name: 'Login',
component: Login
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token') // 获取用户登录状态
if (to.meta.requiresAuth && !isAuthenticated) { // 判断该路由是否需要登录才能访问
next('/login') // 如果没有登录则跳转到登录页面
} else {
next() // 否则放行
}
})
export default router
```
在上面的示例中,我们定义了两个路由,其中Home路由需要用户登录才能访问。我们通过给该路由添加一个自定义字段requiresAuth来标记该路由需要登录才能访问。然后在路由守卫beforeEach中判断该路由是否需要登录才能访问,如果需要且用户没有登录,则跳转到登录页面;否则放行。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)