user.js 2.53 KB
import { login } from '@/api/user'
import store from '../index'
import router, { resetRouter } from '@/router'
import { Message } from "element-ui";
import Cookies from 'js-cookie';
const state = {
    name: Cookies.get('username'),
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    introduction: '',
    userInfo: null
}
const mutations = {
    SET_INTRODUCTION: (state, introduction) => {
        state.introduction = introduction
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_USERINFO: (state, userInfo) => {
        state.userInfo = userInfo
    }
}

const actions = {
    // user login
    login ({ commit }, userInfo) {
        const { username, password, code, num, location } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: username.trim(), password: password, code: code, location: location }).then(response => {
                const { result, code, msg } = response
                if (code === 200) {
                    Cookies.set('token', result.token)
                    commit('SET_USERINFO', result.userInfo)
                    Cookies.set("userInfo", result.userInfo.id, { expires: 720 })
                    Cookies.set("username", result.userInfo.username, { expires: 720 })
                    commit('SET_NAME', result.userInfo.username)
                } else {
                    Message.error(msg);
                }
                resolve(response)
            }).catch(error => {
                reject(error)
            })
        })
    },
    // user logout
    logout ({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            // logout(state.token).then(() => {
            commit('SET_USERINFO', null)
            Cookies.remove("userInfo")
            Cookies.remove("routerTo")
            Cookies.remove('token')
            resetRouter()
            store.dispatch('permission/resetRoutes')
            // reset visited views and cached views
            // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
            dispatch('tagsView/delAllViews', null, { root: true })
            resolve()
        })
    },
    // remove token
    resetToken ({ commit }) {
        return new Promise(resolve => {
            commit('SET_USERINFO', null)
            Cookies.remove("userInfo")
            resolve()
        })
    },
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}