vue中Router路由实现登录后跳转到之前的页面-案例

router.currentRoute:当前的路由信息对象,我们可以通过router.currentRoute.fullPath获得解析后的 URL,包含查询参数和 hash 的完整路径,如果要访问的页面的路由有命名(name)的话,可以通过router.currentRoute.name获得当前路由的名称
router.replace:作用和router.push相同,不过它不会向history添加新纪录,而是替换当前的history记录

思路

首先,我们要把当前的这个路径保存起来,然后在下一步,用户需要登录的时候,直接用这个路由跳转到这个当前的路由就可以。

main.js

router.beforeEach((to, from, next) => {
    if (to.path == '/login') {
    	//保存当前路由
        localStorage.setItem("preRoute", router.currentRoute.fullPath)
    }
    next()
})

登录界面 login.vue

this.$store.dispatch("Login", this.loginForm).then(response => {
	if (response.code == 200) {
		const curr = localStorage.getItem('preRoute')
		if (curr == null) {
			this.$router.push({ path: "/user_center" });
		} else {
			this.$router.push({ path: curr });
		}
		this.$message({ message: response.msg, type: "success", "duration": 1000 });
	} else {
		this.$message.error(response.msg);
	}
}).catch((response) => {
	this.$message.error('请联系管理员!!!');
});

快捷方法

this.$router.go(-1);//上一个

 

posted @   JackieDYH  阅读(70)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示