1.安装Vuex

npm install vuex --save

2. 新建store目录结构

3. 编辑store.js

import Vuex from 'vuex'
import Vue from 'vue'
import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './actions/actions'

Vue.use(Vuex)

// 开发环境
const isDev = process.env.NODE_ENV === 'development'

export default new Vuex.Store({
  strict: isDev, // 开发环境中使用严格模式,防止给Vuex的状态对象直接赋值
  state: defaultState,
  mutations,
  getters,
  actions
})

4. 编辑state.js

export default {
  tokenStatus: true, // token状态
}

5. 编辑mutations.js

export default {
  updateTokenStatus (state, bool) {
    state.tokenStatus = bool
  }
}

PS: getters用于计算属性,actions用于异步操作(暂无使用)

6. 挂载到vue根目录下,编辑main.js

import store from './store/store'

new Vue({
  store,
  router,
  render: h => h(App)
}).$mount('#app')

7. login 登录时,改变state.tokenStatus的值

import { mapMutations } from 'vuex'

methods: {
    // 声明Vuex的mutations的方法
    ...mapMutations(['updateTokenStatus']),
    // 登录方法
    login () {
        ......
        // 改变Vuex.state.tokenStatus的值
        this.updateTokenStatus(true)
    }
}

8. 配置axios的错误判断

// 初始化用户信息
    initUserInfo () {
      const p1 = this.$api.user.getUserInfo()
      p1.then(result => {
        this.data = result
        this.isEdit = false
        this.firstLoading = false
      }).catch(reason => {
        this.firstLoading = false
        this.isEdit = false
        // 目前后端是通过code为-1,返回错误信息
        if (parseInt(reason.code) === -1) {
          this.$alert(reason.message, '提示', { type: 'error' })
        }
      })
    },

9. 拦截响应, 处理401,返回自定义错误

import router from '../../router'
import axios from 'axios'
import localStorage from 'localStorage'
import { MessageBox } from 'element-ui'
import store from '../../store/store'

// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      if (error.response.status === 401) {
        switch (error.response.status) {
          case 401:
            const route = localStorage.getItem('vip_entrance')
            router.replace({
              path: route,
              query: { redirect: router.currentRoute.fullPath }
            })
            if (store.state.tokenStatus) {
              // 饿了么框架弹框
              MessageBox.alert('登录超时!', '提示', { type: 'error' })
              // 修改tokenStatus状态,防止多次点击
              store.commit('updateTokenStatus', false)
            }
            const data = {
              code: 1
            }
            return Promise.reject(data)
        }
      }
    }
    return Promise.reject(error.response.data)
  }
)

 

Logo

前往低代码交流专区

更多推荐