Read all visible cookies:
Cookies.get(); // => { name: 'value' }
Delete cookie:
Cookies.remove('name');
Delete a cookie valid to the path of the current page:
Cookies.set('name', 'value', { path: '' });
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 not raise any exception nor return any value.
Namespace conflicts
If 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 original "window.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' } }
Note: To support IE6-7 (and IE 8 compatibility mode) you need to include the JSON-js polyfill: https://github.com/douglascrockford/JSON-js
更多的可以参考官方说明:
https://github.com/js-cookie/js-cookie
https://www.npmjs.com/package/js-cookie
声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。TEL:177 7030 7066 E-MAIL:11247931@qq.com