vue3用路由实现未登录跳转到登录页面
时间: 2023-11-07 10:12:03 浏览: 107
要实现未登录跳转到登录页面的功能,可以在 Vue3 中使用 Vue Router。具体实现步骤如下:
1. 安装 Vue Router:
```
npm install vue-router
```
2. 在项目中创建一个路由实例:
```
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
// 定义路由
{
path: '/login',
component: Login
},
{
path: '/home',
component: Home,
meta: {
requireAuth: true // 添加该字段,表示进入这个路由是需要登录的
}
}
]
})
export default router
```
这里定义了两个路由,一个是登录页面 `/login`,另一个是需要登录才能访问的页面 `/home`。注意,`/home` 路由添加了一个 `meta` 字段,用来表示该路由需要登录才能访问。
3. 在路由实例中添加一个全局前置守卫:
```
router.beforeEach((to, from, next) => {
if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
if (localStorage.getItem('token')) { // 通过 token 判断是否已经登录
next()
} else {
next({
path: '/login',
query: { redirect: to.fullPath } // 将跳转的路由 path 作为参数,登录成功后跳转到该路由
})
}
} else {
next()
}
})
```
该守卫会在每个路由跳转之前执行,用来判断用户是否已经登录。如果用户已经登录,则直接跳转到目标路由;如果用户未登录,则跳转到登录页面,并将目标路由的 path 作为参数传递过去。
4. 在组件中使用路由跳转:
```
<template>
<div>
<button @click="gotoHome">进入首页</button>
</div>
</template>
<script>
export default {
methods: {
gotoHome() {
this.$router.push('/home')
}
}
}
</script>
```
通过 `this.$router.push('/home')` 可以实现路由跳转。
这样,当用户未登录时,访问需要登录才能访问的页面时,就会被自动跳转到登录页面。