封装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 //以毫秒为单位
    })
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值