使用store进行登录信息管理
其实就是把登录放到vuex
的actions
中去执行,然后保存用户信息、权限等
在store/modules/account.js
中添加如下代码:
import { login, logout, getInfo, menusApi } from '@/api/account';
// getExpiresTime
import {getToken,setToken,removeToken,setUserId,getUserId,removeUserId,setExpiresTime,removeExpiresTime,calcExpiresTime,setPrimissionBtn,getPrimissionBtn,removePrimissionBtn
} from '@/utils/auth';
import { resetRouter } from '@/router';function getMenusList() {const storage = window.localStorage;let menuList = JSON.parse(storage.getItem('menuList'));if (typeof menuList !== 'object' || menuList === null) {menuList = [];}return menuList;
}function setMenusList(menus) {localStorage.setItem('menuList', JSON.stringify(menus));
}const getDefaultState = () => {return {uuid: getUserId(),token: getToken(),name: '',avatar: '',unique_auth: getPrimissionBtn(),menus: getMenusList()};
};const state = getDefaultState();const mutations = {RESET_STATE: (state) => {Object.assign(state, getDefaultState());},SET_UUID: (state, uuid) => {state.uuid = uuid;},SET_TOKEN: (state, token) => {state.token = token;},SET_NAME: (state, name) => {state.name = name;},SET_AVATAR: (state, avatar) => {state.avatar = avatar;},SET_LOGO: (state, logo) => {state.logo = logo;},SET_VERSION: (state, version) => {state.version = version;},SET_UNIQUE_AUTH: (state, unique_auth) => {state.unique_auth = unique_auth;},SET_MENUS: (state, menus) => {state.menus = menus;}
};const actions = {// account loginlogin({ commit }, userInfo) {const { username, password } = userInfo;return new Promise((resolve, reject) => {login({ username: username.trim(), password: password }).then(response => {const { data } = response;const expires = calcExpiresTime(data.expires_time);setToken(data.token, expires);setUserId(data.user_info.id, expires);setExpiresTime(data.expires_time, expires);// 记录用户信息commit('SET_TOKEN', data.token);commit('SET_UUID', data.user_info.id);commit('SET_NAME', data.user_info.account);commit('SET_AVATAR', data.user_info.head_pic);commit('SET_LOGO', data.logo);commit('SET_VERSION', data.version);// 保存菜单及权限信息const btns = data.unique_auth.join(',');commit('SET_UNIQUE_AUTH', btns);commit('SET_MENUS', data.menus);// 存储到本地setMenusList(data.menus);setPrimissionBtn(btns);resolve();}).catch(error => {reject(error);});});},// get account infogetInfo({ commit, state }) {return new Promise((resolve, reject) => {getInfo({ uid: state.uuid }).then(response => {const { data } = response;if (!data) { // token 失效return reject('验证失败, 请重新登录!');}const { id, account } = data;// 更新到state上commit('SET_UUID', id);commit('SET_NAME', account);resolve(data);}).catch(error => {reject(error);});});},// account logoutlogout({ commit, state }) {return new Promise((resolve, reject) => {logout(state.token).then(() => {removeToken(); // must remove token firstremoveUserId();removeExpiresTime();removePrimissionBtn();resetRouter();commit('RESET_STATE');resolve();}).catch(error => {reject(error);});});},// remove tokenresetToken({ commit }) {return new Promise(resolve => {removeToken(); // must remove token firstremoveUserId();removeExpiresTime();commit('RESET_STATE');resolve();});},getMenus({ commit }) {return new Promise((resolve, reject) => {menusApi().then(async res => {resolve(res);commit('SET_MENUS', res.data.menus);// 存储到本地setMenusList(res.data.menus);}).catch(res => {reject(res);});});}
};export default {namespaced: true,state,mutations,actions
};
在utils/auth.js
中添加如下代码:
import Cookies from 'js-cookie';const TokenKey = 'token';
const userIdKey = 'uuid';
const BTNS = 'PERMISSIONBTNS';
const expiresTimeKey = 'expires_time';export function setToken(token, cookieExpires) {return Cookies.set(TokenKey, token, { expires: cookieExpires || 1 });
}
export function getToken() {return Cookies.get(TokenKey);
}
export function removeToken() {return Cookies.remove(TokenKey);
}export function setUserId(uuid, cookieExpires) {return Cookies.set(userIdKey, uuid, { expires: cookieExpires || 1 });
}
export function getUserId() {return Cookies.get(userIdKey);
}
export function removeUserId() {return Cookies.remove(userIdKey);
}export function setExpiresTime(expiresTime, cookieExpires) {return Cookies.set(expiresTimeKey, expiresTime, { expires: cookieExpires || 1 });
}
export function getExpiresTime() {return Cookies.get(expiresTimeKey);
}
export function removeExpiresTime() {return Cookies.remove(expiresTimeKey);
}export function calcExpiresTime(expiresTime) {const nowTimeNum = Math.round(new Date() / 1000);const expiresTimeNum = expiresTime - nowTimeNum;return parseFloat(parseFloat(parseFloat(expiresTimeNum / 60) / 60) / 24);
}// 按钮权限
export function setPrimissionBtn(list) {localStorage.setItem(BTNS, list);
}export function getPrimissionBtn() {return localStorage.getItem(BTNS);
}export function removePrimissionBtn() {localStorage.removeItem(BTNS);
}
在store/index.js
中引入
import account from './modules/account'
const store = new Vuex.Store({modules: {account},......
})
在login/index.vue
中调用account.js
中actions
中的login
调整handleLogin
方法:
handleLogin() {this.$refs.loginForm.validate((valid) => {if (valid) {this.loading = true;this.$store.dispatch('account/login', this.loginForm).then(() => {this.$router.push({ path: this.redirect || '/admin' });this.loading = false;}).catch((err) => {this.loading = false;this.$message.error(err.msg);});} else {return false;}});
}
当然可能点击登录按钮,无法完成跳转,因为接口未返回以下数据,导致报错。
至此完成。。。未有详尽之处,后续迭代