1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > VUE返回上一页不准确 获取上一页URL 当触发返回操作时强制跳转。(增加中转页从后一

VUE返回上一页不准确 获取上一页URL 当触发返回操作时强制跳转。(增加中转页从后一

时间:2023-02-26 23:14:45

相关推荐

VUE返回上一页不准确 获取上一页URL 当触发返回操作时强制跳转。(增加中转页从后一

问题:从具有侧边导航栏的列表页进入详情页,但返回操作时可能是任意导航栏内的页面。也就是说没法正常返回真正的上一页。

// this. r o u t e r . r e p l a c e ( " / " ) ; / / t h i s . router.replace("/"); // this. router.replace("/");//this.router.go(-1);

//window.history.back();

// this.$router.back(-1);

都无法解决这个毛病。

解决思路:首先获得上一页的URL,再替换路由。

参考链接:/Shuanger112/article/details/84862775/

获取上一页的URL:

使用:vue-router的beforeRouterEnter钩子,其实也就是一个路由守卫

beforeRouteEnter(to, from, next) {next(vm=>{// 这里的vm指的就是vue实例,可以用来当做this使用console.log(to) //打印出的是将要去的页面的路由信息参数console.log(from)//打印出的是上一个页面的路由信息参数})}

由此,可以通过from.path得到上一页的url。需要使用,则在App.vue中声明一个lastpage的值。

data() {return {lastpage: "",};},

监听路由器的返回操作,参考链接:/bocongbo/article/details/81667054

整体解决代码:

export default {//获取上一页urlbeforeRouteEnter(to, from, next) {next((vm) => {// 这里的vm指的就是vue实例,可以用来当做this使用vm.lastpage = from.path;console.log(vm.lastpage);});},//监听浏览器返回操作mounted() {if (window.history && window.history.pushState) {history.pushState(null, null, document.URL);window.addEventListener("popstate", this.goBack, false);}},methods:{goBack() {this.$router.replace({path: this.lastpage });},},}

8月27日更新:

用户操作流程:从列表页进入搜索页,再从搜索页进入详情页。

问题分析:由于上述方法是保存当前页面的上页并进行跳转。当用户从详情页回退至搜索页时,搜索页保存的上页url为详情页。当触发返回操作的时候,目的是想让它进入列表页。

解决思路:搜索页只保存从列表页进入的url,无视从详情页返回时获取的lastpage值。

完整解决代码:

export default {//获取上一页urlbeforeRouteEnter(to, from, next) {next((vm) => {// 这里的vm指的就是vue实例,可以用来当做this使用vm.lastpage = from.path;//当检测到不是详情页url时保存到localStorageif (vm.lastpage.indexOf("info") < 0) {localStorage.setItem("lastpageflag", JSON.stringify(vm.lastpage));}});},//监听浏览器返回操作mounted() {if (window.history && window.history.pushState) {history.pushState(null, null, document.URL);window.addEventListener("popstate", this.goBack, false);}},destroyed() {//销毁监听器,否则会扰乱其他页面的监听器window.removeEventListener("popstate", this.goBack, false);},methods:{goBack() {this.lastpageflag = JSON.parse(localStorage.getItem("lastpageflag"));this.$router.replace({path: this.lastpageflag });},},}

VUE返回上一页不准确 获取上一页URL 当触发返回操作时强制跳转。(增加中转页从后一页返回时触发返回操作回到前一页的实现方法)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。