H5 storage, localStorage Data store set validity period

In actual development, cookie storage too affect performance, we usually through localStorage storage to achieve 7 days free login and other functions, but the validity period of localStorage is permanent, here encapsulates a method, directly call to achieve the validity period of localStorage data storage;

// Encapsulate method, Class Storage{constructor() {this.name = 'Storage'} // Set Storage // key: data to be stored // value: data to be stored // SetItem (key,value,expires) {let obj = {value: value,expires: StartTime :new Date().getTime() Localstorage.setitem (key, json.stringify (obj))} // If no valid time is set, Else {localstorage.setitem (key, json.stringify (obj.value))}} getItem(key) {// Define a variable to temporarily store the extracted value Parse (localstorage.getitem (key)) let temp = json.parse (localstorage.getitem (key)) If (temp.expires) {let data = new Date().getTime() if (data-temp.startTime > temp.expires) {// Localstorage. getItem(key) // Return return} else {// Return temp. Value}} // If no value is set, return temp. Else {return temp}}Copy the code

The advantage of this method is convenient data storage, internal encapsulation of the data conversion, no need to store complex data conversion, at the same time through the number of parameters automatically identify whether the need to set the validity period, can be reused in the project;

What better and more efficient way to welcome more exchanges and advice.