需求
vue跳转新页面后,清除url里面的参数,就是上一个页面带过来的参数,只用一次
mounted () {this.$nextTick(() => {let url = this.getnewurl()window.history.replaceState(null, null, url);})},methods: { //根据参数名去清除,可以多个getnewurl () {let url = document.location.href;let reg = /[^\w](url参数名|url参数名)=?([^&|^#]*)/g;url = url.replace(reg, "");reg = /&&/g;url = url.replace(reg, "");reg = /&#/g;url = url.replace(reg, "#");reg = /\?#/g;url = url.replace(reg, "#");// url = url.replaceAll(document.domain,"");// url = url.replaceAll("http://","");// url = url.replaceAll("https://","");reg = /\?#/g;url = url.replace(reg, "#");return url;},
项目场景 使用
点击 登录按钮
调取后端接口
接口返回跳转链接
,前端新窗口打开链接
并调接口将链接中的参数传给后端
,后端返回成功
即页面直接跳转首页
思路
1.点击 登录按钮 调接口 获取到 要跳转的链接 使用 window.open
新页面打开
2.获取到跳转链接后 在mounted 中判断,该链接中 是否有code参数,有则拿到code值,调第二个接口,接口返回成功后,跳转首页
接口返回的跳转链接
http://localhost:8000/?code=AAAAAAAAAAAAAAAAAAAAAA.lniGQWB82wg-ADoYxyfFvcb6mcg.XFAVlY5FaiyOCt0GUHsMkbNw66SkpyD9g1CRIXLJETXjrjPHpYal9gpioxkv2Afo-h_a9-gL_tJHyG8d7TWdYa65GRWe-h1pCdsAvduaJXn9dnOruU5TBcB8lVYIBmPQ6LQfPDQRmt7vpU_aZeYEiBaudfPGrwJekfG5LQd6GrHgcnJUafuLOI6r6Ju9W6cogiXrcfTHDT1B__jXKGiUP0xvn2Y5yvQs6BpmAsqsvMuSgpdYfGz2GFlNpCefDqBltjwRSfL206wTbwczA85FmXSmFbBrESZltIb7DR3Zpc80RDEJ6Q4hAMZbwI7-GK54TPrJQXASqTLqjRhA4oicOw&state=15d57431-f939-4e4a-8006-fab1358cafee9507c217-d512-4f28-a8bf-c16928db80ce%20HTTP/1.1#/login?redirect=%2FHomePage
遇到的问题
当用户点击退出登陆后,页面会跳到带有参数的登录页,而不是一开始的登录页,跳转到带有参数的登录页又会直接进入首页。所以 考虑到这个问题,在代码中加了一步 去掉返回链接中的 参数 功能
这样就可以 点击退出登录 跳转登录页 就不会立马又跳回首页啦
代码
<div class="mg-login"><el-button size="medium" type="primary" style="width: 100%" @click.native.prevent="mgLogin">login in</el-button></div>
mounted() {this.judgeHome() //判断是否要跳转首页},
methods: {// 美光登录按钮mgLogin() {micronLogin().then(res => {window.open(res, "_blank");})},// 美光 登录传codemgCode(params) {let data = {code: params}micronLoginAuth(data).then(res => {if (res.token) {localStorage.setItem("token", res.token)setToken(res.token, false)let url = this.getnewurl()window.history.replaceState(null, null, url);this.$router.push({path: this.redirect || "/",query: { load: 1 },});} else {this.$infoMsg.showErrorMsg(res.msg, this);}}).catch((err) => {console.log(err, 'err.response.data.message')this.$infoMsg.showErrorMsg(err.response.data.message, this);this.loading = false;// this.getCode()});},// 是否直接跳转首页judgeHome() {var url = location.search;//获取url中‘?’符后的if (url.indexOf('?') != -1) {url = url.split("?")[1];}const codeName = url.slice(0, 4)const paramsCode = url.slice(6)if (codeName == 'code') {this.mgCode(paramsCode)} else { }},//根据参数名去清除,可以多个getnewurl() {let url = document.location.hreflet reg = /[^\w](code|state)=?([^&|^#]*)/g;url = url.replace(reg, "");reg = /&&/g;url = url.replace(reg, "");reg = /&#/g;url = url.replace(reg, "#");reg = /\?#/g;url = url.replace(reg, "#");reg = /\?#/g;url = url.replace(reg, "#");return url;}
}