Vue中的Strorage本地化存儲詳解
更新時間:2022年04月29日 15:06:50 作者:是阿嵐吶
這篇文章主要介紹了Vue中的Strorage本地化存儲詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
Storage本地化存儲
存儲優(yōu)點:
- 空間更大:cookie為4kb,storage為5mb
- 節(jié)省網(wǎng)絡(luò)流量:不會發(fā)送數(shù)據(jù)到服務(wù)器,直接存儲在本地
- 快速顯示:存儲在本地的數(shù)據(jù)+瀏覽器本地的緩存,比從服務(wù)器獲取數(shù)據(jù)快得多
localStorage
- 會永久存儲會話數(shù)據(jù),除非手動刪除或者removeItem
- 在所有的同源的窗口中存儲的數(shù)據(jù)是共享的
- 只能存儲字符串類型的數(shù)據(jù),復(fù)雜的對象數(shù)據(jù)必須借助JSON的stringfy和parse處理
sessionStorage
- 在一個會話期內(nèi),存儲會話數(shù)據(jù),當(dāng)關(guān)閉當(dāng)前的會話頁面(瀏覽器頁面)時,數(shù)據(jù)就刪除了
- 存儲的數(shù)據(jù)各會話窗口無法共享
- 只能存儲字符串類型的數(shù)據(jù),復(fù)雜的對象數(shù)據(jù)必須借助JSON的stringfy和parse處理
Strorage本地存儲實例
在model文件夾下面新建一個storage.js
const storage = { set(key,value){ sessionStorage.setItem(key,JSON.stringify(value)); }, get(key){ return JSON.parse(sessionStorage.getItem(key)); }, getForIndex(index){ return sessionStorage.key(index) }, getKeys(){ let items = this.getAll(); let keys = []; for(let index = 0;index<items.length;index++){ keys.push(items[index].key); } }, getLength(){ return sessionStorage.length; }, getSupport(){ return (typeof (Storage) !== "undefined")?true:false; }, remove(key){ sessionStorage.removeItem(key); }, removeAll(){ sessionStorage.clear(); }, getAll(){ let len = sessionStorage.length; let arr = []; for(let i=0;i<len.length;i++){ const getKey = sessionStorage.key(i); const getVal = sessionStorage.getItem(getKey); arr[i] = { "key":getKey, "val":getVal, } } return arr; }, }; export default storage;
創(chuàng)建store
import Vue from "vue"; import Vuex from "vuex"; import storage from "@/model/storage"; Vue.use(Vuex); const store = new Vuex.Store({ state: { // 存儲token token: '', userName: '', roleId:'', staticRoute:[]//這個是本地路由 }, actions: { setuserInfoFun(context, name){ context.commit('setuserInfo', name); }, set_tokenFun(context, token){ context.commit('set_token', token) }, del_tokenFun(context){ context.commit('del_token') }, set_roleIdFun(context,id){ context.commit('set_roleId',id) }, set_routerFun(context,route){ context.commit('set_router',route) } }, // 計算屬性 mutations: { // 修改token,并將token存入localStorage set_token(state, token){ state.token = token; storage.set('token', token); }, del_token(state){ state.token = ""; storage.remove('token'); }, setuserInfo(state, userName){ state.userName = userName; }, set_roleId(state,id){ state.roleId = id; }, set_router(state,router){ state.staticRoute = router; storage.set('route', router); } } }); export default store;
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue實現(xiàn)雙向綁定的原理以及響應(yīng)式數(shù)據(jù)的方法
這篇文章主要介紹了Vue實現(xiàn)雙向綁定的原理以及響應(yīng)式數(shù)據(jù)的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07