极简Vuex存储token、id,并设置请求头同时实现权限分配;

//1.用户登录
1.1data
 data: function () {
     
        return {
     
            userToken: '',
            userID: '',
            param: {
     
                username: '',
                password: ''
            },
            rules: {
     
                username: [{
      required: true, message: '请输入用户名', trigger: 'blur' }],
                password: [{
      required: true, message: '请输入密码', trigger: 'blur' }]
            }
        };
    },
1.2methods
    methods: {
     
        ...mapMutations(['changeLogin', 'changeLoginId']),
        submitForm() {
     
            let obj = {
     
                userName: this.param.username,
                pwd: this.param.password
            };

            this.$refs.login.validate((valid) => {
     
                if (valid) {
     
                    this.$post('/admin/login/index', obj).then((response) => {
     
                        if (response.code == 0) {
     
                            this.$message.success('登录成功');
                            this.userToken = response.data.token;
                            this.userID = response.data.id;
                            this.changeLogin({
      Authorization: this.userToken });
                            this.changeLoginId({
      AuthorizationID: this.userID });
                            this.$router.push({
     
                                path: '/dashboard'
                            });
                        }
                    });
                } else {
     
                    this.$message.error('请输入账号和密码');
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    }
//http response 拦截器 api
axios.interceptors.request.use(
    config => {
     
        if (window.localStorage.getItem('Authorization') && window.localStorage.getItem('AuthorizationID')) {
     
            config.headers.common['X-Token'] = window.localStorage.getItem('Authorization');
            config.headers.common['X-Adminid'] = window.localStorage.getItem('AuthorizationID');
        } else {
     
            console.log(config);
        }
        console.log(config, 'console.log(config);');
        return config;
    },
    error => {
     
        return Promise.reject(error);
    }
);
//这里只是标注  不涉及主题
import {
      post, fetch, patch, put } from './utils/request';
//定义全局变量
Vue.prototype.$post = post;
Vue.prototype.$fetch = fetch;
Vue.prototype.$patch = patch;
Vue.prototype.$put = put;

main.js
import store from './store/index';
new Vue({
     
    router,
    i18n,
    store,
    render: h => h(App)
}).$mount('#app');
router.js
// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location, onResolve, onReject) {
     
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
    return originalPush.call(this, location).catch(err => err);
};
//导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆
router.beforeEach((to, from, next) => {
     
    //debugger
    if (to.path === '/login') {
     
        next();
    } else {
     
        let token = localStorage.getItem('Authorization');
        if (token) {
     
            next();
        } else {
     
            next('/login');
        }
    }
});
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
     
    state: {
     
        //路由权限
        // 存储token
        userId: localStorage.getItem('AuthorizationID') ? localStorage.getItem('AuthorizationID') : '',
        Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : ''
    },
    mutations: {
     
        // 修改token,并将token存入localStorage
        changeLogin(state, user) {
     
            state.Authorization = user.Authorization;
            localStorage.setItem('Authorization', user.Authorization);
        },
        changeLoginId(state, user) {
     
            state.userId = user.Authorization;
            localStorage.setItem('AuthorizationID', user.AuthorizationID);
        }
    }
});
临时笔记  后期备注  有错望纠正  感谢。

你可能感兴趣的:(vue)