我有一个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相关问答推荐

通过另一个文件调用模块化窗口组件

Vue.js编译的render函数不起作用

可组合数据获取示例

有没有办法将react 键作为值传递给由 v-for 创建的 v-model

如何向 添加方法和 v-model?

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

绑定事件在渲染函数中不起作用

将初始值设置为可直接在 HTML 中使用的 vue.js 模型

有没有办法初始化一个保留初始 HTML 的 Vue 对象

使用 vue.js 的 axios 预检失败错误 301

如何获取 Vue 路由历史记录?

将数据传递给另一条路由上的组件

在渲染组件之前从 api 获取数据

如何在生产模式下为 chrome 扩展启用 Vue devtools?

Vue Cli 3 不允许我在 Webpack 中处理 SVG

vue 3 使用 Vuex 和路由的服务器端渲染

如何将事件绑定到 Vuetify 中的树视图 node ?

在路由更改之前显示确认对话框

VueJS 2 在多个组件上debounce

如何使用 Vue Test utils 测试输入是否聚焦?