localstorage store结合存数据

import { login } from 'api/user'
import { Toast } from 'vant'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
// import router from '@/router'

const LOGIN = 'LOGIN'// 获取用户信息
const SetUserData = 'SetUserData'// 获取用户信息
const LOGOUT = 'LOGOUT'// 退出登录、清除用户数据
const USER_DATA = 'userData'// 用户数据
const SetLectureType = 'SetLectureType' // 课程类型

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    user: JSON.parse(localStorage.getItem(USER_DATA) || null),
    lectureType: 1
  },
  mutations: {

    [LOGIN] (state, data) {
      let userToken = data.data
      state.token = userToken
      setToken(userToken)
    },

    [SetUserData] (state, userData = {}) {
      state.user = userData
      localStorage.setItem(USER_DATA, JSON.stringify(userData))
    },
    [SetLectureType] (state, lectureType) {
      state.lectureType = lectureType
    },
    [LOGOUT] (state) {
      state.user = null
      state.token = null
      removeToken()
      localStorage.removeItem(USER_DATA)
      resetRouter()
    }

  },
  actions: {
    async login (state, data) {
      try {
        let res = await login({
          phoneNumber: data.phoneNumber,
          password: data.password
        })
        state.commit(LOGIN, res)
        Toast({
          message: '登录成功',
          position: 'middle',
          duration: 1500
        })
        setTimeout(() => {
          const redirect = data.$route.query.redirect || '/'
          data.$router.replace({
            path: redirect
          })
        }, 1500)
      } catch (error) {
      }
    },
    SetLectureType ({ commit }, lectureType) { // 写入课程类型的筛选id
      commit(SetLectureType, lectureType)
    },
    // get user info
    getInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit(SetUserData, { 'userId': '3301' })
      })
    }
  },
  getters: {
    token (state) {
      return state.token
    },
    user (state) {
      return state.user
    },
    lectureType (state) {
      return state.lectureType
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值