# vue 离开页面跳转 , 询问是否保存的注意事项
# 1.实现效果

# 2. 实现目的
在某种业务场景下,用户不允许跳转到其他页面。于是,需要在用户误操作或者是点击浏览器跳转时提示用户。
# 3. 实现原理
- 使用路由守卫beforeRouteLeave进行控制
- 如果使用浏览器前进后退按钮时注意维持地址栏不变
# 4.代码
<template>
<div>
</div>
</template>
<script>
export default {
beforeRouteLeave (to, from, next) {
// 如果用户更改数据离开页面的情况下,进行弹窗
if (this.orChange) {
// 在离开当前页面给出提示时,发现弹框一闪而过,不能阻止进程(window.confirm原生的是可以的)
//此处必须要加延迟执行
setTimeout(() => {
this.$confirm("您还未保存改动,确定需要提出吗?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(() => {
// 选择确定
next()
}).catch(() => {
// 如果取消跳转地址栏会变化,这时保持地址栏不变
window.history.go(1)
})
}, 200) //此处必须要加延迟执行
} else {
next()
}
}
}
</script>
<style scoped>
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33