vue:登录后跳转到之前要访问的页面(vue@3.3.4)
一,安装pinia
liuhongdi@lhdpc:/data/vue/responsive$ npm -S install pinia
安装完成后查看已安装的版本:
liuhongdi@lhdpc:/data/vue/responsive$ npm list pinia
responsive@0.1.0 /data/vue/responsive
└── pinia@2.1.6
二,代码:
1,store/redirect.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import {defineStore} from 'pinia' //保存登录后要跳转到的页面 export const useRedirectStore = defineStore( "REDIRECT" ,{ state() { return { redirectUrl: '' , } }, //getter getters: { }, //actions actions: { setRedirectUrl(url) { console.log( "set redirecturl:" ); this .redirectUrl = url; } } }) |
2,无权登录时转到登录页
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//跳转到登录页 let redistr = useRouter().currentRoute.value.fullPath; let path = useRouter().currentRoute.value.path; if (path != '/login/login' ) { //保存登录后要跳转的url let storer = useRedirectStore(); storer.setRedirectUrl(redistr); } //跳转到登录页 router.push({ path: "/login/login" }); |
3,登录成功后的跳转:
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
|
let url = "/api/login/login" ; axios({ method: "post" , url:url, data:postData, headers:{ 'Content-Type' : 'multipart/form-data' }, }).then((res) => { if (res.data.code == 0) { ElMessage.success( "登录成功!" ); setUser(res.data); //执行登录成功后需要执行的跳转 let storer = useRedirectStore(); //判断要跳转到的地址 let {redirectUrl} = storeToRefs(storer); if (redirectUrl == '' ) { router.replace({path: "/index/home" }); } else { let url = "/#" +redirectUrl.value; //清空 storer.setRedirectUrl( '' ); //跳转 location.href=url; } } else { ElMessage.error( "error:" +res.data.msg); } } ). catch (err=>{ console.log(err); alert( '网络错误:' +err.message); }); |
三,测试效果:
1,我们访问http://192.168.219.6:8080/#/account/userinfo?id=15
会跳转到登录页:如下::
2,登录后会自动跳转到之前要访问的页面:
如图:
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/03/vue-deng-lu-hou-tiao-zhuan-dao-zhi-qian-yao-fang-wen-de-ye-mian/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
四,查看vue框架的版本:
liuhongdi@lhdpc:/data/vue/responsive$ npm list vue
responsive@0.1.0 /data/vue/responsive
└─┬ vue@3.3.4
└─┬ @vue/server-renderer@3.3.4
└── vue@3.3.4 deduped