我有一个Vue组件,它在"脏"时进行跟踪(例如未保存).如果用户有未保存的数据,我想在他们离开当前表单之前警告他们.在典型的web应用程序中,可以使用onbeforeunload.我试着用这种方法:

mounted: function(){
  window.onbeforeunload = function() {
    return self.form_dirty ? "If you leave this page you will lose your unsaved changes." : null;
  }
}

然而,这在使用Vue路由时不起作用.它将让你导航下尽可能多的路由链接,你想.一旦你试图关闭窗口或导航到real链接,它就会警告你.

有没有办法在Vue应用程序中复制onbeforeunload条普通链路和路由链路?

推荐答案

beforeunload事件一起使用beforeRouteLeave in-component guard.

防护罩通常用于防止使用者意外受伤

在组件定义中,执行以下操作:

beforeRouteLeave (to, from, next) {
  // If the form is dirty and the user did not confirm leave,
  // prevent losing unsaved changes by canceling navigation
  if (this.confirmStayInDirtyForm()){
    next(false)
  } else {
    // Navigate to next view
    next()
  }
},

created() {
  window.addEventListener('beforeunload', this.beforeWindowUnload)
},

beforeDestroy() {
  window.removeEventListener('beforeunload', this.beforeWindowUnload)
},

methods: {
  confirmLeave() {
    return window.confirm('Do you really want to leave? you have unsaved changes!')
  },

  confirmStayInDirtyForm() {
    return this.form_dirty && !this.confirmLeave()
  },

  beforeWindowUnload(e) {
    if (this.confirmStayInDirtyForm()) {
      // Cancel the event
      e.preventDefault()
      // Chrome requires returnValue to be set
      e.returnValue = ''
    }   
  },
},

Vue.js相关问答推荐

在VITE-VUE APP-DEV模式上重定向HTTP请求

无法在cPanel/SSH上构建 | Laravel + Vue优化

如何在vue js模板中添加foreach和for循环

v-on 的 .native 修饰符仅在组件上有效,但在 标签上使用

VueJS3 - 在 for 循环中获取元素的句柄

如果单元格不可见,则以编程方式打开行的编辑模式. Ag 网格,Vue.js

Webpack - MiniCssExtractPlugin 不提取文件

VuetifyJS:如何摆脱 v-stepper 组件的提升?

vuetifyjs:仅添加使用过的图标来构建

在下拉菜单上使用箭头键滚动

将检测外部点击自定义指令从 Vue 2 迁移到 Vue 3

使用 Vue Router 设置页面标题

Vue.js 中 Chrome 和 Datalist 的性能问题

VueRouter 未定义

使用 VueJS 在 v-for 中转换

验证子组件Vue vee-validate

我在 Nuxt 2.14.0 中运行的是什么版本的 Vue?

从我的服务访问路由实例

vue组件中导入和使用three.js库

Vuejs获取事件正在调用的元素?