這次帶給大家如何操作JS Cookie插件,操作JS Cookie插件的注意事項有哪些,以下就是實戰案例,一起來看一下。
Cookie是網站設計者放置在客戶端的小文字文件,一般後台語言使用的比較多,可以實現使用者個人化的一些需求。 js-cookie插件是一個JS操作cookie的插件,原始檔只有3.34 KB,非常輕量級。 js-cookie也支援npm和Bower安裝和管理。以下來看看js-cookie的具體用法。
A simple, lightweight JavaScript API for handling cookies
Works in all browsers
Accepts any character
Heavily tested
No dependency
Unobtrusive JSON support
Supports AMD/CommonJS
RFC 6265 compliant
Useful Wiki
Enable custom encoding/decoding
~900 bytes gzipped!
#參考方法:
1 、引入js-cookie.js1.直接飲用cdn:
2.本地下載下來後:
3.模組化開發時: import Cookies from 'js-cookie'
#2、js-cookie.js常用的API與方法a、設定cookie
Cookies.set('name', 'value', { expires: 7, path: '' });//7天過期
//設定一個jsonb、讀取cookie
//取得cookie
#讀取所有的cookiec、刪除cookie
#刪除cookie時必須是同一個路徑。
Basic Usage
Create a cookie, valid across the entire site:
# Cookies.set('name', 'value');Create a cookie that expires 7 days from now, valid across the entire site:
Create an expiring cookie, valid to the path of the current page:
Read cookie:
Cookies.get('nothing'); // => undefinedCookies.get(); // => { name: 'value' }Read all visible cookies:
#Delete cookie:
Delete a cookie valid to the path of the current page:
Cookies.remove('name'); // fail!Cookies.remove('name', { path: '' }); // removed!
IMPORTANT! When deleting a cookie, you must pass the exact same path and domain attributes that were used to set the cookie, unless you're relying on the default attributes.
Note: Removing a nonexistent cookie does notento doyet return any value.
Namespace conflictsIf there is any danger of a conflict with the namespace Cookies, the noConflict method will allow you to define a new namespace and preserve the original one. This is especially useful when running the script on third party sites e.g. as part of a widget or SDK.
// Assign the js-cookie api to a different variable and restore the origariable and restore the orig。 Cookies"
var Cookies2 = Cookies.noConflict();Cookies2.set('name', 'value');Note: The .noConflict method is not necessary when using AMD or CommonJS, thus it is not exposed in those environments.
JSON
js-cookie provides unobtrusive JSON storage for cookies.
When creating a cookie you can pass an Array or Object Literal instead of a string in the value. If you do so, js-cookie will store the string representation of the object according to JSON.stringify:
Cookies.set('name', { foo: 'bar' });
When reading a cookie with the default Cookies.get api, you receive the string representation stored in the cookie:
Cookies.get('name'); // => '{"foo":"bar"}' Cookies.get(); // => { name: '{"foo":"bar"}' }
When reading a cookie with the Cookies.getJSON api, you receive the parsed representation of the string stored in the cookie according to JSON.parse:
Cookies.getJSON('name'); // => { foo: 'bar' } Cookies.getJSON(); // => { name: { foo: 'bar' } }
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
以上是如何操作JS Cookie插件的詳細內容。更多資訊請關注PHP中文網其他相關文章!