首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Vue.js 2应用程序卸载之前,我如何模拟mimic?

在Vue.js 2应用程序卸载之前,我如何模拟mimic?
EN

Stack Overflow用户
提问于 2019-06-11 18:57:25
回答 2查看 18.6K关注 0票数 18

我有一个Vue组件,它在“脏”(例如未保存)时进行跟踪。如果用户有未保存的数据,我想在他们从当前表单浏览之前警告他们。在典型的web应用程序中,您可以使用onbeforeunload。我曾经尝试过像这样在安装中使用它:

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

然而,当使用Vue路由器时,这是不起作用的。它将允许您导航到尽可能多的路由器链接,你想。一旦您试图关闭窗口或导航到一个真正的链接,它将警告您。

是否有方法在Vue应用程序中复制onbeforeunload,用于正常链接和路由器链接?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-11 21:03:36

使用beforeRouteLeave 组件内保护beforeunload事件。

离开保护通常用于防止用户意外离开路由时未保存的编辑。可以通过调用next(false)取消导航。

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

代码语言:javascript
复制
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 = ''
    }   
  },
},
票数 41
EN

Stack Overflow用户

发布于 2022-01-08 16:45:15

完全模仿这一点的最简单的解决方案如下:

代码语言:javascript
复制
{
  methods: {
    beforeWindowUnload (e) {
      if (this.form_dirty) {
        e.preventDefault()
        e.returnValue = ''
      }
    }
  },
  beforeRouteLeave (to, from, next) {
    if (this.form_dirty) {
      next(false)
      window.location = to.path // this is the trick
    } else {
      next()
    }
  },
  created () {
    window.addEventListener('beforeunload', this.beforeWindowUnload)
  },
  beforeDestroy () {
    window.removeEventListener('beforeunload', this.beforeWindowUnload)
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56550164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档