简单用户管理系统(P-13)

处理token和存储到vuex

cd 到client 中安装jwt-decode cnpm install jwt-decode 安装好了
那么你在登陆页直接可以解析token

const decoded = jwt_decode(token) ;
14781769-07f7bc04125bb073.png
image.png

现在可以将解析的东西放在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); 

···


14781769-3b12ecd98cbc21b9.png
image.png

在根位置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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值