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

本文详细介绍了在Vue.js应用中,如何处理从具有侧边导航栏的列表页进入详情页后,返回操作可能无法正常回到上一页的难题。通过在beforeRouteEnter钩子中获取上一页URL,并在监听浏览器返回操作时,根据用户操作流程动态保存和恢复上一页路径,确保返回操作能正确返回列表页。同时,针对用户从搜索页返回的情况,特别处理了保存的lastpage值,避免错误回退到详情页。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:从具有侧边导航栏的列表页进入详情页,但返回操作时可能是任意导航栏内的页面。也就是说没法正常返回真正的上一页。
// 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,再替换路由。

参考链接:https://blog.csdn.net/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: "",
    };
  },

监听路由器的返回操作,参考链接:https://blog.csdn.net/bocongbo/article/details/81667054
整体解决代码:

export default {
//获取上一页url
	  beforeRouteEnter(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 });
	    },
	}}

2021年8月27日更新:
用户操作流程:从列表页进入搜索页,再从搜索页进入详情页。
问题分析:由于上述方法是保存当前页面的上页并进行跳转。当用户从详情页回退至搜索页时,搜索页保存的上页url为详情页。当触发返回操作的时候,目的是想让它进入列表页。
解决思路:搜索页只保存从列表页进入的url,无视从详情页返回时获取的lastpage值。

完整解决代码:

export default {
//获取上一页url
	  beforeRouteEnter(to, from, next) {
		    next((vm) => {
	      //  这里的vm指的就是vue实例,可以用来当做this使用
	      vm.lastpage = from.path;
	      //当检测到不是详情页url时保存到localStorage
	      if (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 });
	    },
	}}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值