【Vue | ElementUI】Vue离开当前页面时弹出确认框实现

Vue离开当前页面时弹出确认框实现

1. 实现目的

在某种业务场景下,用户不允许跳转到其他页面。于是,需要在用户误操作或者是点击浏览器跳转时提示用户。

2. 实现原理

  1. 使用路由守卫beforeRouteLeave进行控制
  2. 如果使用浏览器前进后退按钮时注意维持地址栏不变
<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>

猜你喜欢

转载自www.cnblogs.com/axiangcoding/p/11913254.html
今日推荐