In single page application, how to store data and get data after refresh the page [closed]

二次信任 提交于 2019-12-12 02:22:56

问题


Recently I have a problem with how to store data on a single page application.

I want to ask how to store data and get the data back after refresh page in a Single Page Application.

For example, I get 'user name' and it is shown on the navigation bar, but after I refresh the page, the 'user name' is gone. The 'user name' is a javascript variable.

Before refresh

After refresh

Could anyone give some suggestions about how and where to store the data ?

In the localStorage or somewhere else? What should be a standard or proper way?

Also, another way is fetch data again from server every time after the page refresh, is this a proper way?

BTW, I am using Vue.js.

Thanks


回答1:


The right way is with sessionStorage, because when your browser is closed the variable will be deleted

 // Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');

// Remove saved data from sessionStorage
sessionStorage.removeItem('key')

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage




回答2:


The sessionStorage object is similar to localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab. As per your requirement, this seems more suitable.

Example :

if (sessionStorage.clickcount) {
      sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
      sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";


来源:https://stackoverflow.com/questions/39750948/in-single-page-application-how-to-store-data-and-get-data-after-refresh-the-pag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!