简体   繁体   English

在重新加载或关闭 vue.js 之前做一些事情

[英]Do something before reload or close in vue.js

I have a Vue.JS application with a beforeDestroy method that I'm trying to use to store some data in local storage before the app closes or is reloaded.我有一个一Vue.JS应用beforeDestroy方法,我试图用存储在本地存储数据的一些应用程序关闭前或重新加载。

Just for reference:仅供参考:

beforeDestroy: function() {
  localStorage.setItem('preference', this.preference);
  ...
}

However, neither closing nor reloading the app actually calls this method.但是,关闭或重新加载应用程序实际上都不会调用此方法。

How can I make sure this method is called before the app is closed?如何确保在关闭应用程序之前调用此方法?

What is it that "closes" or "reloads" the app? “关闭”或“重新加载”应用程序是什么? Is it the user in the browser closing the window and/or refreshing the page?是浏览器中的用户关闭窗口和/或刷新页面吗?

If that is the case, nothing is "destroyed" and that function won't run.如果是这种情况,则不会“破坏”任何内容,并且该功能将不会运行。

You would have to define a onbeforeunload function globally:您必须全局定义一个onbeforeunload函数:

window.onbeforeunload = function(){
    return "Are you sure you want to close the window?";
}

Then you can save items to local storage inside that function before the return statement.然后,您可以在 return 语句之前将项目保存到该函数内的本地存储中。

Note: don't define it inside your beforeDestroy function, because again, that just won't run when you reload the page or navigate away.注意:不要在beforeDestroy函数中定义它,因为同样,当你重新加载页面或导航离开时,它不会运行。

Understand this question is quite old but if I'm out there searching for it, someone else is!了解这个问题已经很老了,但是如果我在那里寻找它,那么其他人就是!

Unfortunately, as far I can tell there is nothing in Vue that can currently hook into before the user reloads the page either via closing, CMD+R, selecting a new URL etc.不幸的是,据我所知,在用户通过关闭、CMD+R、选择新 URL 等重新加载页面之前,Vue 中目前没有任何东西可以挂钩。

The best solution, if it's sensitive data and you really want them to think about what they are doing, you can do the below which is taken from this medium post.最好的解决方案,如果它是敏感数据并且您真的希望他们考虑他们在做什么,您可以执行以下操作,该操作取自这篇中等文章。

<script>
 export default {
      data: () => ({
    isEditing: false
  })
  beforeMount() {
    window.addEventListener("beforeunload", this.preventNav)
  },

  methods: {
    preventNav(event) {
      if (!this.isEditing) return
      event.preventDefault()
      event.returnValue = ""
    }
  }
}
</script>

This will at least bring up a dialogue box asking if they are really sure they want to reload the page.这至少会弹出一个对话框,询问他们是否真的确定要重新加载页面。

Note the text of the dialogue box cannot be altered.请注意,对话框的文本不能更改。 A good description of what is going on with the dialogue box text is contained in this StackOverflow question.这个StackOverflow 问题中包含了对对话框文本正在发生的事情的很好的描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM