如何在Vue.js 2应用程序中模仿onbeforeunload? [英] How can I mimic onbeforeunload in a Vue.js 2 application?

查看:43
本文介绍了如何在Vue.js 2应用程序中模仿onbeforeunload?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Vue component that is tracking when it is "dirty" (e.g. unsaved). I would like to warn the user before they browse away from the current form if they have unsaved data. In a typical web application you could use onbeforeunload. I've attempted to use it in mounted like this:

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

但是,在使用Vue Router时,这不起作用.它可以让您向下浏览任意数量的路由器链接.一旦您尝试关闭窗口或导航到 real 链接,就会警告您.

However this doesn't work when using Vue Router. It will let you navigate down as many router links as you would like. As soon as you try to close the window or navigate to a real link, it will warn you.

是否可以在Vue应用程序中为普通链接和路由器链接复制 onbeforeunload ?

Is there a way to replicate onbeforeunload in a Vue application for normal links as well as router links?

推荐答案

使用 beforeRouteLeave

Use the beforeRouteLeave in-component guard along with the beforeunload event.

请假护板通常用于防止用户意外保留未保存的修改路线.导航可以取消通过调用next(false).

The leave guard is usually used to prevent the user from accidentally leaving the route with unsaved edits. The navigation can be canceled by calling next(false).

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

In your component definition do the following:

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 2应用程序中模仿onbeforeunload?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆