JavaScript开发小技巧之cookie

设置cookie


export const setCookie = (key, value, expire) => {
    const d = new Date();
    d.setDate(d.getDate() + expire);
    document.cookie = `${key}=${value};expires=${d.toUTCString()}`
};

读取cookie


export const getCookie = (key) => {
    const cookieStr = unescape(document.cookie);
       const arr = cookieStr.split('; ');
       let cookieValue = '';
       for (let i = 0; i < arr.length; i++) {
           const temp = arr[i].split('=');
           if (temp[0] === key) {
               cookieValue = temp[1];
               break
       }
    }
    return cookieValue
};

删除cookie


export const delCookie = (key) => {
    document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
};
以上是编程学习网小编为您介绍的“JavaScript开发小技巧之cookie”的全面内容,想了解更多关于 vuejs 内容,请继续关注编程基础学习网。

本文标题为:JavaScript开发小技巧之cookie

基础教程推荐