What is localStorage
For browsers, using Web Storage to store key values is more intuitive than storing cookies, and has a larger capacity, which includes two types: localStorage and sessionStorage
- sessionStorage (temporary storage) : maintains a storage area for each data source that exists during browser opening, including page reloading of localStorage (long-term storage) : the same as sessionStorage, but the data will still exist
after the browser is closed
Ii. Usage
Note: The usage of sessionStorage and localStorage is basically the same. The value of the reference type needs to be converted to JSON, so only localStorage is listed here
1 save
//object
const info = { name: 'hou', age: 24, id: '001' };
//String
const str="haha";
localStorage.setItem('hou', JSON.stringify(info));
localStorage.setItem('zheng', str);
const str="haha";
localStorage.setItem('hou', JSON.stringify(info));
localStorage.setItem('zheng', str);
2 for
var data1 = JSON.parse(localStorage.getItem('hou'));
var data2 = localStorage.getItem('zheng');
3 remove
//detel one
localStorage.removeItem('hou');
//Detel all
localStorage.clear();
4 listening
Storage Triggered when a change (add, update, delete) occurs, changes on the same page will not be triggered, but will only listen for changes on other pages in the same domain. Storage
window.addEventListener('storage', function (e) {
console.log('key', e.key); console.log('oldValue', e.oldValue);
console.log('newValue', e.newValue); console.log('url', e.url);
})
5. Practice in VUE
A default based on what I want to do, remember what I did last time, very simple
when I add data, remember what I did last time
when I add or commit,
localStorage.setItem('projectId',me.workhourData.projectId+","+me.workhourData.projectManager);
Just grab it when you open the new page, and just make sure it’s not empty
//Remember the last selected auditor
if(localStorage.length>0){
var mydata = localStorage.getItem('projectId');
if(mydata!=null){
var arr3=mydata.split(",");
if(arr3[0]==me.workhourData.projectId){
me.workhourData.projectManager=arr3[1];
}
}
}
Note 6 points
The localStorage expiration date is permanent. The average browser can store around 5MB. The sessionStorage API is the same as localStorage.
sessionStorage defaults to the session time of the browser (that is, after the TAB closes, it disappears).
localStorage scope is the protocol, hostname, port.
sessionStorage scope is window, protocol, hostname, port.
once you know these points, your problem will be solved easily.
localStorage is on the window. So you don’t need to write this.localstorage, in vue if you write this, it means the vUE instance. complains