处理token和存储到vuex
cd 到client 中安装jwt-decode cnpm install jwt-decode
安装好了
那么你在登陆页直接可以解析token
const decoded = jwt_decode(token) ;
现在可以将解析的东西放在vuex
那么你需要在store.js中保存这个信息,但是我现在没有看懂
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const types = {
SET_IS_AUTHENTICATED: 'SET_IS_AUTHENTICATED', // 是否认证通过
SET_USER: 'SET_USER'
};
const state = {
isAuthenticated: false, //默认是没有授权的
user: {}
};
// 获取状态信息
const getters = {
isAuthenticated: state => state.isAuthenticated,
user: state => state.user
};
// 更改状态信息
const mutations = {
[types.SET_IS_AUTHENTICATED](state, isAuthenticated){
if(isAuthenticated) {
state.isAuthenticated = isAuthenticated;
} else {
state.isAuthenticated = false;
}
},
[types.SET_USER](state, user){
if(user) {
state.user = user;
} else {
state.user = {};
}
}
};
// 异步操作的actions
const actions = {
setAuthenticated: ({commit}, isAuthenticated) => {
commit(types.SET_IS_AUTHENTICATED, isAuthenticated);
},
setUser: ({commit}, user) => {
commit(types.SET_USER, user);
}
};
export default new Vuex.Store({
state,
getters,
mutations,
actions
})
解析token,然后保存
···
// 解析token
const decoded = jwt_decode(token);
// console.log(decoded);
// token 解析存储到vuex中
this.$store.dispatch("setAuthenticated", !this.isEmpty(decoded)); // 空的时候取反
this.$store.dispatch("setUser", decoded);
···
在根位置app.vue中保存
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
import jwt_decode from 'jwt-decode';
export default {
name: 'app',
created() {
// 在根位置保存这个信息,否则刷新会丢失
if (localStorage.eleToken) {
const decoded = jwt_decode(localStorage.eleToken);
this.$store.dispatch('setAuthenticated', !this.isEmpty(decoded));
this.$store.dispatch('setUser', decoded);
}
},
methods: {
isEmpty(value) {
return (
value === undefined ||
value === null ||
(typeof value === "object" && Object.keys(value).length === 0) ||
(typeof value === "string" && value.trim().length === 0)
)
}
}
}
</script>
<style>
html,body,
#app {
width: 100%;
height: 100%;
}
</style>