天天看點

封裝localStorage設定失效時間

storage.js:

var Storage = {
    //設定緩存
    setItem(params){
        let obj = {
            name:'',
            value:'',
            expires:"",
            startTime:new Date().getTime()//記錄何時将值存入緩存,毫秒級
        }
        let options = {};
        //将obj和傳進來的params合并
        Object.assign(options,obj,params);
        if(options.expires){
        //如果options.expires設定了的話
        //以options.name為key,options為值放進去
            localStorage.setItem(options.name,JSON.stringify(options));
        }else{
        //如果options.expires沒有設定,就判斷一下value的類型
               let type = Object.prototype.toString.call(options.value);
               //如果value是對象或者數組對象的類型,就先用JSON.stringify轉一下,再存進去
            if(Object.prototype.toString.call(options.value) == '[object Object]'){
                options.value = JSON.stringify(options.value);
            }
            if(Object.prototype.toString.call(options.value) == '[object Array]'){
                options.value = JSON.stringify(options.value);
            }
            localStorage.setItem(options.name,options.value);
        }
    },
    //拿到緩存
    getItem(name){
        let item = localStorage.getItem(name);
        //先将拿到的試着進行json轉為對象的形式
        try{
            item = JSON.parse(item);
        }catch(error){
        //如果不行就不是json的字元串,就直接傳回
            item = item;
        }
        //如果有startTime的值,說明設定了失效時間
        if(item.startTime){
            let date = new Date().getTime();
            //何時将值取出減去剛存入的時間,與item.expires比較,如果大于就是過期了,如果小于或等于就還沒過期
            if(date - item.startTime > item.expires){
            //緩存過期,清除緩存,傳回false
                localStorage.removeItem(name);
                return false;
            }else{
            //緩存未過期,傳回值
                return item.value;
            }
        }else{
        //如果沒有設定失效時間,直接傳回值
            return item;
        }
    },
    //移出緩存
    removeItem(name){
        localStorage.removeItem(name);
    },
    //移出全部緩存
    clear(){
        localStorage.clear();
    }
}
//參考CSDN: https://blog.csdn.net/zhaoxiang66/article/details/86703438
export default Storage
           

全局引入Storage,在main.js中:

import storage from "../static/js/storage"
Vue.prototype.$storage = storage;
           

用到的地方:

this.$storage.setItem({
		name:"aaa",
		age: 24,
		expires: 1000 * 60 * 60 *24 //以毫秒為機關
    })