UNPKG

ptool

Version:

vue项目开发通用工具类封装

62 lines (61 loc) 1.95 kB
"use strict"; /** * @FileName cookie.ts * @Author Mad Dragon <395548460@qq.com> * @Version V 0.0.1 * @Date 2021/4/13 11:33 * @Title Cookie操作 * @Desc **/ Object.defineProperty(exports, "__esModule", { value: true }); /** * 设置cookie * @param name * @param value * @param hours * @param path */ const setCookie = (name, value, hours, path) => { const expires = new Date(); expires.setTime(expires.getTime() + hours * 3600000); const expiresTxt = typeof hours === 'string' ? '' : `;expires=${expires.toUTCString()}`; document.cookie = `${escape(name)}=${escape(value)}${expiresTxt}${path === '' ? '' : `;path=${path}`}`; }; /** * 获取cookie值 * @param name */ const getCookieValue = (name) => { let nameTxt = escape(name); // 读cookie属性,这将返回文档的所有cookie const allCookies = document.cookie; // 查找名为name的cookie的开始位置 nameTxt += '='; const pos = allCookies.indexOf(nameTxt); // 如果找到了具有该名字的cookie,那么提取并使用它的值 if (pos !== -1) { // 如果pos值为-1则说明搜索'version='失败 const start = pos + nameTxt.length; // cookie值开始的位置 let end = allCookies.indexOf(';', start); // 从cookie值开始的位置起搜索第一个';'的位置,即cookie值结尾的位置 if (end === -1) end = allCookies.length; // 如果end值为-1说明cookie列表里只有一个cookie // 提取cookie的值 return allCookies.substring(start, end); // 对它解码 } return ''; // 搜索失败,返回空字符串 }; /** * 删除cookie * @param name * @param path */ const deleteCookie = (name, path) => { const expires = new Date(0); document.cookie = `${escape(name)}=;expires=${expires.toUTCString()}${path === '' ? '' : `;path=${path}`}`; }; exports.default = { setCookie, getCookieValue, deleteCookie };