user.js 868 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
import { Login } from "@/api/user";
import { getToken, setToken } from "@/utils/auth";

const getDefaultState = () => {
  return {
    token: getToken()
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    return (state.token = token);
  }
};

const actions = {
  login({ commit }) {
    return new Promise((resolve, reject) => {
      Login()
        .then(res => {
          if (res.code === 0) {
            const token = res.data;
            commit("SET_TOKEN", token);
            setToken(token);
            resolve();
          } else {
            reject(res);
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};