本节主要内容:解析token里面的数据并存储到vuex中。
1、安装解析token的模块
-
到客户端
cd client
-
安装
npm install jwt-decode
2、解析token里面的数据
-
解析(到Login.vue里面去)
- 引入解析模块
import jwt_decode from 'jwt-decode';
- 在登录成功跳转之前解析token,打印出来,判断是否成功解析
解析token// 解析token const decoded = jwt_decode(token); console.log(decoded);
- 引入解析模块
3、存储到vuex中
-
vuex的准备,打开client/src/store.js
import Vue from 'vue' import Vuex from 'vuex' import { type } from 'os'; Vue.use(Vuex); const types = { SET_AUTHENTICATED:"SET_AUTHENTICATED",//这个在浏览器中显示,以此来判断认证是否通过 SET_USER:"SET_USER" } const state = { isAuthenticated:false, user:{} } const getters = { isAuthenticated:state=>state.isAuthenticated, user:state=>state.user } const mutations = { [types.SET_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 = {}; } } const actions = { setAuthenticated:({commit},isAuthenticated) => { commit(types.SET_AUTHENTICATED,isAuthenticated); }, setUser:({commit},user) => { commit(types.SET_USER,user); } } export default new Vuex.Store({ state, getters, mutations, actions })
-
测试
-
存储到vuex中,打开Login.vue
-
新增加一个判空方法
// 判断是否为空,空值返回false,真值返回true isEmpty(value){ return( value === undefined || value === null || (typeof value === "object" && Object.keys(value).length === 0) || (typeof value === "string" && value.trim().length === 0) );
-
- token存储到vuex中
```javascript
// token存储到vuex中
this.$store.dispatch("setAuthenticated",!this.isEmpty(decoded));
this.$store.dispatch("setUser",decoded);
```
token存储到vuex中
-
测试
测试
发现登录之后再次刷新,标红部分会消失,这是由于刷新的时候根组件没有进行判断
- 打开client/src/App.vue,写入以下内容,再次刷新的时候不会再消失了,isAuthenticated会为true
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
import jwt_decode from 'jwt-decode';
export default {
name: "app",
components: {},
created () {
if(localStorage.eleToken){
const decoded = jwt_decode(localStorage.eleToken);
// token存储到vuex中
this.$store.dispatch("setAuthenticated",!this.isEmpty(decoded));
this.$store.dispatch("setUser",decoded);
}
},
methods: {
// 判断是否为空,空值返回false,真值返回true
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>
网友评论