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