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
|