Cookie to Cookie (JS-cookie plug-in)
Introduction to a.
npm install js-cookie --save
Copy the code
2. References
import Cookies from 'js-cookie'
Copy the code
Three. General use
1. Save to Cookie
// 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:
Cookies.set('name'.'value', { expires: 7 });
// Create an expiring cookie, valid to the path of the current page:
Cookies.set('name'.'value', { expires: 7.path: ' ' });
Copy the code
2. Take out the Cookie
// Read cookie:
Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined
// Read all visible cookies:
Cookies.get(); // => { name: 'value' }
Copy the code
3. Delete
// 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!
Copy the code
4. Special use (storing objects in cookies)
The Cookie format is converted from a string to a JSON format.
const user = {
name: 'lia'.age: 18
}
Cookies.set('user', user)
const liaUser = JSON.parse(Cookies.get('user'))
Copy the code
Refer to the link