vue3 vue-router 登录成功前往首页
时间: 2023-08-04 10:15:51 浏览: 55
在 Vue3 中使用 Vue Router 实现登录成功后跳转到首页的方法如下:
1. 在路由配置文件中定义需要登录才能访问的页面路由,例如:
```javascript
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home,
meta: {
requireAuth: true // 需要登录才能访问
}
},
{
path: '/login',
name: 'Login',
component: Login
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
```
2. 在路由导航守卫中判断用户是否已经登录,如果没有登录则跳转到登录页面,例如:
```javascript
import router from './router'
router.beforeEach((to, from, next) => {
if (to.meta.requireAuth && !isLogin()) { // 判断该页面是否需要登录
next({
path: '/login',
query: { redirect: to.fullPath } // 保存用户本来要访问的页面
})
} else {
next()
}
})
function isLogin() {
// 判断用户是否已经登录
// 如果已经登录返回 true,否则返回 false
}
```
3. 在登录成功后,通过 `$router.push` 方法跳转到保存的用户本来要访问的页面,例如:
```javascript
methods: {
login() {
// 登录成功后跳转到首页
this.$router.push({ path: '/', query: { redirect: this.$route.fullPath } })
}
}
```
这样就可以在用户登录成功后跳转到首页了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)