123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- import {
- getInfo,
- login,
- loginPhone,
- logout
- } from '@/api/user'
- import {
- getToken,
- removeToken,
- setToken
- } from '@/utils/auth'
- import {
- EventBus,
- Events
- } from '@/utils/event-bus'
- import store from '@/store'
- const user = {
- state: {
- token: getToken(),
- user: null
- },
- mutations: {
- SET_TOKEN: (state, token) => {
- state.token = token
- uni.setStorageSync('token', token)
- setToken(token)
- },
- SET_USER: (state, user) => {
- state.user = user
- uni.setStorageSync('user', user)
- EventBus.$emit(Events.USER_INFO_UPDATE, {
- 'user': user
- })
- },
- SET_PHONE: (state, phone) => {
- state.phone = phone
- }
- },
- actions: {
- // 短信登录
- loginPhone({
- commit,
- dispatch
- }, userInfo) {
- return new Promise((resolve, reject) => {
- loginPhone(userInfo).then(response => {
- const data = response.data
- commit('SET_TOKEN', data.token)
- commit('SHOW_LOADING')
- dispatch('getInfo')
- resolve()
- }).catch(error => {
- reject(error)
- })
- })
- },
- // 登录
- login({
- commit,
- dispatch,
- state
- }, userInfo) {
- userInfo.username = userInfo.username.trim()
- return new Promise((resolve, reject) => {
- login(userInfo).then(response => {
- const data = response.data
- commit('SET_TOKEN', data.token)
- commit('SHOW_LOADING')
- dispatch('getInfo')
- resolve()
- }).catch(error => {
- reject(error)
- })
- })
- },
- // 获取用户信息
- getInfo({
- commit,
- state
- }, params) {
- return new Promise((resolve, reject) => {
- params = params || {}
- getInfo(params).then(response => {
- const data = response.data
- commit('SET_USER', data)
- store.commit('HIDE_LOADING')
- resolve(response)
- }).catch(error => {
- reject(error)
- store.commit('HIDE_LOADING')
- })
- })
- },
- // 登出
- logout({
- commit,
- dispatch,
- state
- }) {
- return new Promise((resolve, reject) => {
- logout().then(() => {
- resolve()
- dispatch('fedLogOut')
- }).catch(error => {
- reject(error)
- dispatch('fedLogOut')
- })
- })
- },
- // 前端 登出
- fedLogOut({
- commit
- }) {
- return new Promise(resolve => {
- removeToken()
- commit('SET_TOKEN', '')
- commit('SET_USER', null)
- resolve()
- })
- }
- }
- }
- export default user
|