登录后重定向到原先路由原创
# 编写对应vue文件
# login.vue
<template>
... // 登录组件
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import { postUserLogin } from '@/api/controller/UserController';
import router from '@/router';
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";
const route = useRoute()
/**
* 按钮loading
*/
const loading = ref<boolean>(false);
const formState = reactive<UserLoginRequest>({
userAccount: '',
userPassword: '',
});
/**
* 登录
*/
function onSubmit() {
loading.value = true;
postUserLogin(formState).then((res:any) => {
if (res.code === 0) {
localStorage.setItem('token', res.data.token);
const query: LocationQuery = route.query;
const redirect = (query.redirect as LocationQueryValue) ?? "/";
const otherQueryParams = Object.keys(query).reduce(
(acc: any, cur: string) => {
if (cur !== "redirect") {
acc[cur] = query[cur];
}
return acc;
},
{}
);
router.push({ path: redirect, query: otherQueryParams }).then(() => {
message.success('登录成功');
loading.value = false;
})
}
}).catch((err) => {
loading.value = false;
});
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# redirect.vue
<template>
<div ></div>
</template>
<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const { params, query } = route;
const { path } = params;
router.replace({ path: '/' + path, query });
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# router.js定义路由
{
path: '/login',
name: 'Login',
component: () => import('@/views/gen/login/index.vue')
},
{
path: "/redirect/:path(.*)",
component: () => import("@/views/gen/redirect/index.vue"),
},
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 路由守卫使用
import router from "@/router";
// 白名单路由
const whiteList = ["/login"];
router.beforeEach(async (to, from, next) => {
const hasToken = localStorage.getItem("token");
if (hasToken) {
if (to.path === "/login") {
next({ path: "/" });
} else {
// 未匹配到任何路由,跳转404
if (to.matched.length === 0) {
from.name ? next({ name: from.name }) : next("/404");
} else {
next();
}
}
} else {
// 未登录可以访问白名单页面
if (whiteList.indexOf(to.path) !== -1) {
next();
} else {
next(`/login?redirect=${to.path}`);
}
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
上次更新: 2025/02/18 14:46:10
- 01
- 模板生成工具 原创02-18
- 02
- RTC实时时钟 原创02-12
- 03
- keil调试 原创01-21
- 04
- GPIO概述与配置 原创01-20
- 05
- element-plus多文件手动上传 原创11-03