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

查看:41
本文介绍了如何在 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 时不起作用.它可以让您根据需要导航尽可能多的路由器链接.只要您尝试关闭窗口或导航到真实链接,它就会警告您.

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 组件内保护 以及 beforeunload 事件.

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天全站免登陆