Vue离开当前页面时弹出确认框实现
1. 实现目的
在某种业务场景下,用户不允许跳转到其他页面。于是,需要在用户误操作或者是点击浏览器跳转时提示用户。
2. 实现原理
- 使用路由守卫beforeRouteLeave进行控制
- 如果使用浏览器前进后退按钮时注意维持地址栏不变
<template> <div> </div> </template> <script> export default { beforeRouteLeave (to, from, next) { this.$confirm('正在离开本页面,本页面内所有未保存数据都会丢失', '警告', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { next() }).catch(() => { // 如果取消跳转地址栏会变化,这时保持地址栏不变 window.history.go(1) }) } } </script> <style scoped> </style>