vue实现cookie
Vue 中实现 Cookie 操作
在 Vue 项目中操作 Cookie 可以通过原生 JavaScript 的 document.cookie 或第三方库(如 js-cookie)实现。以下是两种方法的详细说明:
使用原生 JavaScript 操作 Cookie
原生方式通过 document.cookie 直接读写 Cookie,但需要手动处理字符串格式。
设置 Cookie
document.cookie = 'key=value; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/';
expires设置过期时间(UTC 格式)。path指定 Cookie 生效路径。
读取 Cookie

const cookies = document.cookie.split(';').reduce((acc, cookie) => {
const [key, value] = cookie.trim().split('=');
acc[key] = value;
return acc;
}, {});
console.log(cookies.key); // 输出指定 Cookie 值
删除 Cookie 通过设置过期时间为过去的时间点实现删除:
document.cookie = 'key=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
使用 js-cookie 库
js-cookie 提供了更简洁的 API,适合 Vue 项目集成。
安装

npm install js-cookie
引入与使用
import Cookies from 'js-cookie';
// 设置 Cookie
Cookies.set('key', 'value', { expires: 7, path: '/' }); // 过期时间 7 天
// 读取 Cookie
const value = Cookies.get('key');
// 删除 Cookie
Cookies.remove('key', { path: '/' });
在 Vue 组件中的示例
将 Cookie 操作封装为 Vue 的可复用方法:
// utils/cookie.js
import Cookies from 'js-cookie';
export const setCookie = (key, value, options = {}) => {
Cookies.set(key, value, options);
};
export const getCookie = (key) => {
return Cookies.get(key);
};
export const removeCookie = (key) => {
Cookies.remove(key);
};
组件内调用
import { setCookie, getCookie } from '@/utils/cookie';
export default {
methods: {
handleLogin() {
setCookie('auth_token', '12345', { expires: 1 });
},
checkAuth() {
const token = getCookie('auth_token');
if (!token) this.$router.push('/login');
}
}
};
注意事项
- 安全性:敏感数据(如用户令牌)应设置为
HttpOnly和Secure(仅 HTTPS)。 - 作用域:明确指定
path和domain避免跨路径问题。 - SSR 兼容:若使用 Nuxt.js 等服务端渲染框架,需通过
process.client判断环境:if (process.client) { const token = Cookies.get('token'); }






