使用js-cookie依赖包
更多参考:https://www.npmjs.com/package/js-cookie
- 安装
cnpm install js-cookie --save
- 使用
import cookies from 'js-cookie' // 设置cookie
cookies.set('name', 'value')
cookies.set('name', 'value', { expires: days }) // 获取cookie
cookies.get('name') // 删除cookie
cookies.remove('name')
自己封装cookie的操作方法
- 建立cookie.js
// 获取cookie
export function getCookie(key) {
var arr = []
var reg = new RegExp('(^| )' + key + '=([^;]*)(;|$)')
arr = document.cookie.match(reg)
if (arr) {
return decodeURIComponent(arr[2])
} else {
return null
}
} // 设置cookie
export function setCookie(key, value, expiredays) {
var expires = new Date()
expires.setDate(expires.getDate() + expiredays)
document.cookie =
key +
'=' +
encodeURIComponent(value) +
(expiredays ? ';expires=' + expires.toGMTString() : '')
} // 删除cookie
export function delCookie(key) {
var expires = new Date()
expires.setTime(expires.getTime() - 1)
var value = getCookie(key)
if (value != null) {
document.cookie = key + '=' + value + ';expires=' + expires.toGMTString()
}
}
2. 使用
> ```
> import { getCookie, setCookie, delCookie } from './cookie.js'
>
> setCookie(key, value, expiredays)
> getCookie(key)
> delCookie(key)
> ```