vue怎么实现未登录就跳到登录页
时间: 2023-09-04 15:15:05 浏览: 45
Vue可以通过导航守卫来实现未登录状态下跳转到登录页的功能。导航守卫是Vue Router提供的一种钩子函数,用于在路由跳转前进行一些操作。
可以在路由配置中设置beforeEach导航守卫函数来判断用户是否已登录,如果未登录则跳转到登录页,如下所示:
```javascript
const router = new VueRouter({
routes: [
{
path: '/login',
component: Login
},
{
path: '/home',
component: Home,
meta: {
requireAuth: true // 需要登录才能访问的页面
}
}
]
});
router.beforeEach((to, from, next) => {
if (to.meta.requireAuth && !isLogin()) { // 判断是否需要登录
next({
path: '/login',
query: { redirect: to.fullPath } // 记录当前路由,登录成功后跳转到该路由
});
} else {
next();
}
});
function isLogin() {
// 判断用户是否已登录
return localStorage.getItem('token');
}
```
在上述代码中,`beforeEach`函数会在每次路由跳转前被调用,如果需要登录才能访问的页面没有登录,则会跳转到登录页,并记录当前路由,登录成功后再跳转回来。`isLogin`函数用于判断用户是否已登录,可以根据自己的实际情况来实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)