vue 中如何判断返回操作(包括浏览器的返回按钮)?
我的需求:
- 先从列表=>详情页
- 如果在详情页点击的返回按钮,则读取之前缓存的历史数据
(在详情页刷新后再点击返回,也符合条件)
此时的返回包括:
- 浏览器的返回按钮
- 页面中的按钮(调用router.back()/go(-1)等路由方法)
要如何全局判断用户进行了返回操作呢?
回答:
用Vuex:
详情页:
beforeRouteLeave(to, from, next) { if (this.$store.state.refreshed) {
this.$store.commit('setRefreshed', false);
}
next();
}
列表页:
beforeRouteEnter(to, from, next) { if (from.path === '/details' && this.$store.state.refreshed) {
// 读取缓存数据
} else {
// 重新获取数据
}
next();
}
最后,在详情页的刷新按钮的点击事件里,把 refreshed 设置成 true。
methods: { refresh() {
this.$store.commit('setRefreshed', true);
// 刷新详情页
}
}
回答:
你需要的是类似于App开发中的 页面栈
,传统的网页开发中没有这个概念,可以尝试采用以下插件实现:
- vue-page-stack
- stack-keep-alive
以上是 vue 中如何判断返回操作(包括浏览器的返回按钮)? 的全部内容, 来源链接: utcz.com/p/934717.html