login.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import Vue from 'vue';
  2. import Vuex from 'vuex';
  3. import _ from 'lodash';
  4. import { Notification } from 'element-ui';
  5. const jwt = require('jsonwebtoken');
  6. Vue.use(Vuex);
  7. const api = {
  8. interface: `/api/train/login`,
  9. user: id => `/api/train/user/update/${id}`,
  10. bind: `/api/train/user/bind`,
  11. };
  12. const state = () => ({});
  13. const mutations = {};
  14. const actions = {
  15. async login({ commit }, { user, router, path = '/', needReturn = false }) {
  16. const res = await this.$axios.$post(`${api.interface}`, user);
  17. if (res.errcode === 0) {
  18. let user = jwt.decode(res.data);
  19. if (user.type == process.env.VUE_APP_USER_TYPE) {
  20. localStorage.setItem('user', JSON.stringify(user));
  21. commit('setUser', user, { root: true });
  22. Notification({
  23. title: '登录成功',
  24. message: `欢迎,${user.name}`,
  25. type: 'success',
  26. duration: 2000,
  27. });
  28. if (needReturn) return res;
  29. else {
  30. router.push(path);
  31. }
  32. } else {
  33. Notification({
  34. title: '请重新登陆',
  35. message: `原因:非当前端用户,需要重新登陆`,
  36. type: 'warning',
  37. });
  38. console.warn('非当前端用户,需要重新登陆');
  39. }
  40. } else {
  41. if (needReturn) return res;
  42. else {
  43. Notification({
  44. title: '登录失败',
  45. message: `失败原因:${res.errmsg}`,
  46. type: 'error',
  47. });
  48. }
  49. }
  50. },
  51. async update({ commit }, { id, ...info }) {
  52. let res = await this.$axios.$post(`${api.user(id)}`, info);
  53. return res;
  54. },
  55. async bind({ commit }, payload) {
  56. let res = await this.$axios.$post(`${api.bind}`, payload);
  57. return res;
  58. },
  59. };
  60. export default {
  61. namespaced: true,
  62. state,
  63. mutations,
  64. actions,
  65. };