极简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);
        }
    }
});
临时笔记  后期备注  有错望纠正  感谢。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值