web 本地存儲(chǔ) (localStorage、sessionStorage)
對(duì)瀏覽器來(lái)說(shuō),使用 Web Storage 存儲(chǔ)鍵值對(duì)比存儲(chǔ) Cookie 方式更直觀,而且容量更大,它包含兩種:localStorage 和 sessionStorage
sessionStorage(臨時(shí)存儲(chǔ)) :為每一個(gè)數(shù)據(jù)源維持一個(gè)存儲(chǔ)區(qū)域,在瀏覽器打開(kāi)期間存在,包括頁(yè)面重新加載
localStorage(長(zhǎng)期存儲(chǔ)) :與 sessionStorage 一樣,但是瀏覽器關(guān)閉后,數(shù)據(jù)依然會(huì)一直存在
API
sessionStorage 和 localStorage 的用法基本一致,引用類(lèi)型的值要轉(zhuǎn)換成JSON
1.保存數(shù)據(jù)到本地
const info = {
? ? ? ? name: 'Lee',
? ? ? ? age: 20,
? ? ? ? id: '001'
? ? };
? ? sessionStorage.setItem('key', JSON.stringify(info));
? ? localStorage.setItem('key', JSON.stringify(info));
2. 從本地存儲(chǔ)獲取數(shù)據(jù)
var data1 = JSON.parse(sessionStorage.getItem('key'));
var data2 = JSON.parse(localStorage.getItem('key'));
3. 本地存儲(chǔ)中刪除某個(gè)保存的數(shù)據(jù)
sessionStorage.removeItem('key');
localStorage.removeItem('key');
4. 刪除所有保存的數(shù)據(jù)
sessionStorage.clear();
localStorage.clear();
5. 監(jiān)聽(tīng)本地存儲(chǔ)的變化
Storage 發(fā)生變化(增加、更新、刪除)時(shí)的 觸發(fā),同一個(gè)頁(yè)面發(fā)生的改變不會(huì)觸發(fā),只會(huì)監(jiān)聽(tīng)同一域名下其他頁(yè)面改變 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);
? ? })