cookie #
操作 cookie
的相关方法
getCookie #
获取 cookie 值
接收一个
key
值,返回它在cookie
中对应的value
函数参数和返回值
js
/**
* @param {string} name cookie的key
* @return {string} cookie的值
*/
展示源码
ts
export const getCookie = (name: string): string => {
if (name) {
return Cookie.get(name);
}
throw Error('getCookie(name: string & required)');
};
代码用例
js
const myCookie = getCookie('id');
setCookie #
设置 cookie 值
接收一个
key
value
并按照options
的配置将其储存在cookie
中
函数参数和返回值
js
/**
* @param {string} name cookie的key
* @param {string} value cookie的值
* @param {Date | number} [CookieOptions.expires]
* @param {string} [CookieOptions.path]
* @param {string} [CookieOptions.domain]
* @param {boolean} [CookieOptions.secure]
* @param {'Lax' | 'Strict' | 'None'} [CookieOptions.sameSite]
* @return 无返回值
*/
展示源码
ts
export const setCookie = (name: string, value: string, options: CookieOptions = {}): void => {
if (name && value) {
const { expires, path, domain, secure } = options;
if (!expires) {
options.expires = 7;
} else if (typeof expires === 'string') {
throw Error('expires must be string or Date');
}
if (!path) {
options.path = '/';
}
if (!domain) {
options.domain = window.location.hostname;
}
if (!secure) {
options.secure = false;
}
Cookie.set(name, value, options);
return;
}
throw Error('setCookie(name: string & required, value: string & required)');
};
代码用例
js
setCookie('id', 'qwertyuiop11213', { expires: '2023-08-29T08:24:11.265Z' });
hasCookie #
接收一个值并判断是否存在以该值为 key
的 cookie
函数参数和返回值
js
/**
* @param {string} name 要判断的key
* @return {boolean}
*/
展示源码
ts
export const hasCookie = (name: string): boolean => {
return !!getCookie(name);
};
代码用例
js
const hasIdCookie = hasCookie('id');
removeCookie #
接收一个 name
并移除以其为 key
的 Cookie
。
该函数可配置
options
对象。
函数参数和返回值
js
/**
* @param {string} name cookie的key
* @param {Date | number} [CookieOptions.expires]
* @param {string} [CookieOptions.path]
* @param {string} [CookieOptions.domain]
* @param {boolean} [CookieOptions.secure]
* @param {'Lax' | 'Strict' | 'None'} [CookieOptions.sameSite]
* @return 无返回值
*/
展示源码
ts
export const removeCookie = (name: string, options?: CookieOptions): void => {
if (name) {
Cookie.remove(name, options);
!options?.domain?.startsWith('.') &&
Cookie.remove(
name,
Object.assign({}, options, {
domain: '.' + options.domain
})
);
return;
}
throw Error('removeCookie(name: string & required)');
};
代码用例
js
removeCookie('id');