在某些特定情况下,项目可能不需要使用
Cookie
,此时可以选择使用localStorage
来替代。
首先,在 package.json
文件中删除与 Cookie
相关的依赖,如 "js-cookie": "3.0.1"
。
在 main.js
、store/modules/app.js
、utils/auth.js
和 login.vue
文件中,移除对 Cookies
的导入:
import Cookies from 'js-cookie'
将 main.js
文件中涉及到 Cookies.get
的地方替换为 localStorage.getItem
:
Vue.use(Element, {
size: localStorage.getItem('size') || 'medium' // 设置 element-ui 的默认尺寸
})
在 utils/auth.js
文件中,用 localStorage
替换 Cookies
的相关操作:
const TokenKey = 'Admin-Token'
export function getToken() {
return localStorage.getItem(TokenKey)
}
export function setToken(token) {
return localStorage.setItem(TokenKey, token)
}
export function removeToken() {
return localStorage.removeItem(TokenKey)
}
在 store/modules/app.js
中,将所有 Cookies
相关的代码替换为 localStorage
:
const state = {
sidebar: {
opened: localStorage.getItem('sidebarStatus') ? !!+localStorage.getItem('sidebarStatus') : true,
withoutAnimation: false,
hide: false
},
device: 'desktop',
size: localStorage.getItem('size') || 'medium'
}
const mutations = {
TOGGLE_SIDEBAR: state => {
if (state.sidebar.hide) {
return false;
}
state.sidebar.opened = !state.sidebar.opened
state.sidebar.withoutAnimation = false
localStorage.setItem('sidebarStatus', state.sidebar.opened ? 1 : 0)
},
CLOSE_SIDEBAR: (state, withoutAnimation) => {
localStorage.setItem('sidebarStatus', 0)
state.sidebar.opened = false
state.sidebar.withoutAnimation = withoutAnimation
},
TOGGLE_DEVICE: (state, device) => {
state.device = device
},
SET_SIZE: (state, size) => {
state.size = size
localStorage.setItem('size', size)
},
SET_SIDEBAR_HIDE: (state, status) => {
state.sidebar.hide = status
}
}
在 login.vue
文件中,将涉及 Cookies
的部分替换为 localStorage
:
getCookie() {
const username = localStorage.getItem("username");
const password = localStorage.getItem("password");
const rememberMe = localStorage.getItem('rememberMe')
this.loginForm = {
username: username === null ? this.loginForm.username : username,
password: password === null ? this.loginForm.password : decrypt(password),
rememberMe: rememberMe === null ? false : Boolean(rememberMe)
};
},
handleLogin() {
this.refs.loginForm.validate(valid => {
if (valid) {
this.loading = true;
if (this.loginForm.rememberMe) {
localStorage.setItem("username", this.loginForm.username);
localStorage.setItem("password", encrypt(this.loginForm.password));
localStorage.setItem('rememberMe', this.loginForm.rememberMe);
} else {
localStorage.removeItem("username");
localStorage.removeItem("password");
localStorage.removeItem('rememberMe');
}
this.store.dispatch("Login", this.loginForm).then(() => {
this.$router.push({ path: this.redirect || "/" }).catch(() => {});
}).catch(() => {
this.loading = false;
if (this.captchaEnabled) {
this.getCode();
}
});
}
});
}
通过上述步骤,你可以成功地将若依框架中的 Cookie
操作替换为 localStorage
,以满足不同的项目需求。
powered by kaifamiao