vue 实现页面返回
监听浏览器返回事件
使用 window.addEventListener 监听 popstate 事件,在 Vue 的 mounted 钩子中绑定事件,并在 beforeDestroy 钩子中移除监听。
mounted() {
window.addEventListener('popstate', this.handleBack);
},
beforeDestroy() {
window.removeEventListener('popstate', this.handleBack);
},
methods: {
handleBack() {
// 自定义返回逻辑,例如路由跳转或数据恢复
this.$router.go(-1);
}
}
使用 Vue Router 的导航守卫
通过 beforeRouteLeave 守卫实现返回时的数据保存或逻辑拦截。

beforeRouteLeave(to, from, next) {
// 可在此处缓存页面数据或询问用户是否确认离开
if (confirm('确定要离开吗?')) {
next();
} else {
next(false); // 取消导航
}
}
编程式导航
通过 $router.go() 或 $router.back() 控制返回行为。

methods: {
goBack() {
this.$router.go(-1); // 返回上一页
// 或使用 this.$router.back();
}
}
缓存页面状态
结合 <keep-alive> 和 Vue Router 的 meta 字段实现页面状态缓存。
// router.js 配置
routes: [
{
path: '/detail',
component: Detail,
meta: { keepAlive: true } // 标记需要缓存的页面
}
]
<!-- App.vue 中使用 keep-alive -->
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
移动端手势返回
监听触摸事件实现滑动返回(需配合 CSS 过渡效果)。
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX;
},
handleTouchEnd(e) {
const endX = e.changedTouches[0].clientX;
if (endX - this.startX > 100) { // 右滑超过阈值
this.$router.back();
}
}
}
<div
@touchstart="handleTouchStart"
@touchend="handleTouchEnd"
>
滑动区域
</div>






