在重新加载或在vue.js中关闭之前执行某些操作 [英] Do something before reload or close in vue.js

查看:308
本文介绍了在重新加载或在vue.js中关闭之前执行某些操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 beforeDestroy 方法的Vue.JS应用程序,我试图在应用程序关闭或重新加载之前将一些数据存储在本地存储中。仅供参考:

I have a Vue.JS application with a beforeDestroymethod that I'm trying to use to store some data in local storage before the app closes or is reloaded. 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?

推荐答案

什么是关闭或重新加载 '应用程序?是浏览器中的用户关闭窗口还是刷新页面?如果是这种情况,则不会销毁任何内容,并且该功能将无法运行。您必须在全局范围内定义 onbeforeunload 函数:

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:

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

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

然后你可以在return语句之前将项目保存到该函数内的本地存储。

then you can save items to local storage inside that function before the return statement.

提示:不要在里面定义它你的beforeDestroy函数,因为再次,当你重新加载页面或导航时它不会运行。

hint: don't define it inside your beforeDestroy function, because again, that just wont run when you reload the page or navigate away.

这篇关于在重新加载或在vue.js中关闭之前执行某些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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