js-cookie.js的使用

鵬歌歌發表於2018-07-24

引入js-cookie.js:

  • 直接引用cdn:
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
複製程式碼
  • 本地下載下來:
<script src="/js/js.cookie.js"></script>
複製程式碼
  • 模組化開發時:
import Cookies from 'js-cookie'
複製程式碼

js-cookie.js常用的API和方法

  • 設定cookie
Cookies.set('name', 'value', { expires: 7, path: '' }); //7天過期

Cookies.set('name', { foo: 'bar' }); //設定一個json
複製程式碼
  • 讀取cookie
Cookies.get('name'); //獲取cookie

Cookies.get(); //讀取所有的cookie
複製程式碼
  • 刪除cookie
Cookies.remove('name'); //刪除cookie時必須是同一個路徑。
複製程式碼

自己寫

  getsec (str) {
    let str1 = str.substring(1, str.length) * 1;
    let str2 = str.substring(0, 1);
    if (str2 == "s") {
      return str1 * 1000;
    } else if (str2 == "h") {
      return str1 * 60 * 60 * 1000;
    } else if (str2 == "d") {
      return str1 * 24 * 60 * 60 * 1000;
    }
  },
  // Set the cookie
  setCookie (name, value, time, path, domain) {
    let strsec = this.getsec(time);
    let exp = new Date();
    exp.setTime(exp.getTime() + strsec * 1);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=" + path + ";domain=" + domain;
  },
  // Read cookies
  getCookie (name) {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) return unescape(arr[2]);
    else return null;
  },
  // Remove cookies
  delCookie () {
    let exp = new Date();
    exp.setTime(exp.getTime() - 1);
    let cval = this.getCookie(name);
    if (cval !== null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
  },
複製程式碼