react 封裝本身的Cookie庫

const cookie = {
//根據key值獲取對應的cookie getCookie(key: any) {
//獲取cookie const data = document.cookie
//獲取key第一次出現的位置 let startIndex = data.indexOf(key + '=')
//若是開始索引值大於0表示有cookie if (startIndex > -1) {
//key的起始位置等於出現的位置加key的長度+1 startIndex = startIndex + key.length + 1
//結束位置等於從key開始的位置以後第一次;號所出現的位置 let endIndex = data.indexOf(';', startIndex)
//若是未找到結尾位置則結尾位置等於cookie長度,以後的內容所有獲取 endIndex = endIndex < 0 ? data.length : endIndex return decodeURIComponent(data.substring(startIndex, endIndex)) } else { return '' } }, setCookie(key: any, value: any, time?: any) { //默認保存時間 const times = time //獲取當前時間 const cur = new Date() /設置指定時間 cur.setTime(cur.getTime() + times * 24 * 3600 * 1000) //建立cookie 而且設置生存週期爲UTC時間 document.cookie = key+'=' +encodeURIComponent(value) +';expires=' +(times === undefined ? '' : cur.toUTCString()) }, delCookie(key: any) {
//獲取cookie const data = this.getCookie(key)
//若是獲取到cookie則從新設置cookie的生存週期爲過去時間 if ((data as any) !== false) { this.setCookie(key, data, -1) } } } export default cookie
相關文章
相關標籤/搜索