You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue JS中如何借助JavaScript处理onbeforeunload逻辑实现HTML标签表单提交

Vue中实现onbeforeunload关闭页面提醒

不要直接给window.onbeforeunload赋值,否则会覆盖其他地方绑定的同事件逻辑,建议用事件监听的方式绑定,组件卸载时记得移除事件避免内存泄漏。

选项式API(Vue2/Vue3都支持)

export default {
  mounted() {
    window.addEventListener('beforeunload', this.handlePageUnload)
  },
  beforeUnmount() {
    window.removeEventListener('beforeunload', this.handlePageUnload)
  },
  methods: {
    handlePageUnload(e) {
      const dialogText = '你有未保存的修改,确定要离开吗?'
      e.returnValue = dialogText
      return dialogText
    }
  }
}

组合式API(Vue3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:09:01