Vue 页面回退保留滚动位置以及其他数据
go(-1): 原页面表单中的内容会丢失:
1. this.$router.go(-1):后退+刷新;
2. this.$router.go(0):刷新;
3. this.$router.go(1):前进;
----
back(): 原页表表单中的内容会保留;
1. this.$router.back():后退 ;
2. this.$router.back(0):刷新;
3. this.$router.back(1):前进;
一般没有复杂的回退功能这几种方法就可以实现,但是在平时的项目中可能会有比较复杂的功能,例如回退时需要保存跳转前的数据(分页管理的页码值等),这时就可以通过以下方法来实现。
将下列方法放在app.vue文件下,方便所以页面都可以调用。
// provide: 指定要传递给子孙组件的数据
provide() {
return {
pushRouterToHistory: this.pushRouterToHistory,
setRouteHistory: this.setRouteHistory,
};
},
// 将屏幕高度,以及所需数据保存在数组中
pushRouterToHistory(route) {
let scrollTop = document.documentElement.scrollTop;
this.history.push({ route, scrollTop });
},
// 后退按钮点击方法
goBack() {
let route = this.history.pop();
if (route) {
this.$router.push(route.route);
this.$nextTick(() => {
document.documentElement.scrollTop = route.scrollTop;
});
} else {
this.$router.push("/?token=" + sessionStorage.getItem("oatoken"));
document.documentElement.scrollTop = 0;
}
},
接下来就需要在子页面定义跳转所需要的数据
// 子页面通过 inject 方法导入在app.vue中向外传递的方法,接下来就可以直接使用
inject: ["pushRouterToHistory"],
// 跳转时将需要的数据存起来
routerGo(path) {
let route = this.$route;
let params = this.$route.params;
route = {
path: this.$route.path,
query: { ...this.$route.query, ...this.searchParams },
params,
};
this.pushRouterToHistory(route);
this.$router.push(path);
},
// 页面加载时将数据进行回显(例如分页数据),之后在发起请求即可
mounted() {
let query = this.$route.query;
for (let key in this.searchParams) {
this.searchParams[key] = query[key] || this.searchParams[key];
}
this.searchParams.page = Number(this.searchParams.page || 1);
this.searchParams.size = Number(this.searchParams.size || 10);
}