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

2023-03-10,,

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

1. 实现目的

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

2. 实现原理

    使用路由守卫beforeRouteLeave进行控制
    如果使用浏览器前进后退按钮时注意维持地址栏不变
<template>
<div>
</div>
</template> <script>
export default {
beforeRouteLeave (to, from, next) {
// 这里需要elementui的支持,如果使用其他界面组件自行替换即可
this.$confirm('正在离开本页面,本页面内所有未保存数据都会丢失', '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 正常跳转
next()
}).catch(() => {
// 如果取消跳转地址栏会变化,这时保持地址栏不变
window.history.go(1)
})
}
}
</script> <style scoped> </style>

【Vue | ElementUI】Vue离开当前页面时弹出确认框实现的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。