一、安装
npm install js-cookie --save
二、引用
import Cookies from 'js-cookie'
三、一般使用
存到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: '' });
2.在Cookie中取出
// Read cookie:
Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined
// Read all visible cookies:
Cookies.get(); // => { name: 'value' }
3.删除
// 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!
四、特殊使用(在Cookie中存对象)
跟一般使用不同的是,从Cookie中取出的时候,要从字符串转换成json格式:
const user = {
name: 'lia',
age: 18
}
Cookies.set('user', user)
const liaUser = JSON.parse(Cookies.get('user'))
五、打包成单独文件
1.配置文件:website.js
export default {
cookieKeys: {
user_id: 'user_id',
}
}
2.存储文件名:cookiestore.js
import Cookies from 'js-cookie'//引用js-cookie插件
import website from '@/const/website'//调用配置文件
function get(key) {
return Cookies.get(key, { domain: document.domain.split('.').slice(-2).join('.'), path: '/' })
}
function set(key, value) {
return Cookies.set(key, value, { domain: document.domain.split('.').slice(-2).join('.'), path: '/' })
}
function remove(key) {
return Cookies.remove(key, { domain: document.domain.split('.').slice(-2).join('.'), path: '/' })
}
// 需要管理的cookie值
export function getUserId() {
return get(website.cookieKeys.user_id)
}
export function setUserId(user_id) {
return set(website.cookieKeys.user_id, user_id)
}
export function removeUserId() {
return remove(website.cookieKeys.user_id)
}
//删除建立的cookie
export function removeAll() {
removeUserId()
}
3.具体应用界面
import {setUserId,getUserId,removeUserId,removeAll} from '@/utils/cookiestore'//第二步建立的文件
export default {
created() {
var user_id = getUserId()
...
}
}
网友评论