原生JS的全局对象cookie和localStorage重新封装

项目中经常用到的方法,放这边省的写其他项目用到了还要重新写或者翻以前项目
cookie:【微信公众号里面使用的cookie看这里,这个不适用公众号cookie操作封装】

const setCookie = (name, value, expire) => {
	let date = new Date();
	date.setSeconds(date.getSeconds() + expire);
	document.cookie = name + " = " + escape(value) + "; expires=" + date.toGMTString();
};

const getCookie = (name) => {
	var arr;
	const reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
	arr = document.cookie.match(reg);
	if (arr) {
		return unescape(arr[2]);
	} else {
		return null;
	}
};
//读取cookies 
const readCookie = (name) => {
	let arr = null
	let reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
	if (document.cookie && (arr = document.cookie.match(reg))) {
		return unescape(arr[2])
	} else {
		return null;
	}
}

const delCookie = (name) => {
	let exp = new Date();
	exp.setTime(exp.getTime() - 1);
	let cval = getCookie(name);
	if (cval != null) {
		document.cookie = name + " = " + cval + "; expires=" + exp.toGMTString();
	}
};

export default {
	setCookie,
	getCookie,
	readCookie,
	delCookie
};

localStorage:

const setItem = function(key, value) {
	if (value == null || value == undefined || value == 'undefined') {
		localStorage.setItem(key, value)
    }else{
		localStorage.setItem(key, JSON.stringify(value))
	}
}

const getItem = function(key) {
    let value = localStorage.getItem(key)
    if (value == null || value == undefined || value == 'undefined') {
        return ''
    }
    return JSON.parse(value)
}

const removeItem = function(key) {
    if (!key) {
        return
    }
    localStorage.removeItem(key)
}

const clearAll = function() {
    localStorage.clear()
}

export default {
    setItem,
    getItem,
    removeItem,
    clearAll
}

你可能感兴趣的:(js,javascript)