vue3 script setup 使用导航守卫,离开页面前提示数据未保存

vue3使用导航守卫

文章目录

  • 前言
  • 一、相关文档
  • 二、使用示例


前言

vue3 使用 < script setup >语法糖,页面数据已编辑未保存时,离开当前页面前添加导航守卫,弹窗提示数据未保存。


一、相关文档

vue3 script setup 使用导航守卫,离开页面前提示数据未保存_第1张图片
导航守卫 Vue Router


二、使用示例

代码如下:

// 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)
        })
    }
})

你可能感兴趣的:(前端学习,vue.js,前端)