Vue3 阻止页面跳转


Vue3 阻止页面跳转

当数据未保存,用户想要跳转其他页面时,可以做以下操作。提醒用户

第一步监听网页,例如刷新,关闭窗口,或跳转到其他页面的情况

<script setup>
import { onMounted, onBeforeUnmount } from 'vue'

const handleBeforeUnload = (event) => {
  const message = '你有未保存的更改,确定要离开吗?'
  event.returnValue = message // 这是为了在浏览器中显示提示
  return message // 一些浏览器(例如 Chrome)也会使用这个消息
}

// 页面加载时,添加事件监听
onMounted(() => {
  window.addEventListener('beforeunload', handleBeforeUnload)
})

// 页面卸载时,移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload)
})
</script>

第二步,Vue3 内部的路由跳转 onBeforeRouteLeave

<script setup>
import { onBeforeRouteLeave } from 'vue-router'

onBeforeRouteLeave((to, from, next) => {
  const isSaved = false // 假设这是一个标记,判断是否保存了数据

  if (!isSaved) {
    const confirmLeave = window.confirm('你有未保存的更改,确定要离开吗?')
    if (confirmLeave) {
      next() // 允许导航
    } else {
      next(false) // 阻止导航
    }
  } else {
    next() // 如果已保存,允许导航
  }
})
</script>

做这两个步骤即可。能够阻止用户跳转其他页面


文章作者: 冷杨威
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 冷杨威 !
  目录
-->