vue3使用导航守卫
vue3 使用 < script setup >语法糖,页面数据已编辑未保存时,离开当前页面前添加导航守卫,弹窗提示数据未保存。
代码如下:
// watch监听数据变化
watch(state.info.orderInfo, (newVal, oldVal) => {
// 数据变化时标记flag为true;数据保存时标记flag为false
editFlag.value = true
console.log(newVal, oldVal)
})
// 监听跳转,添加路由守卫拦截
onBeforeRouteLeave((to, from, next) => {
if(editFlag.value){
ElMessageBox.confirm(
'当前页面修改数据为保存,确定离开吗?',
'温馨提示',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(() => {
// 点击确定,忽略修改,继续跳转
next()
})
.catch(() => {
// 点击取消,拦截跳转,停留在当前页面
next(false)
})
}
})