vite2 + vue3 + vue-router4 + vuex4 + element-plus 实战(三)-axios和vuex

安装axios和vuex

yarn add axios vuex@next

简单封装axios

  1. 在src目录下新建utils文件夹
  2. utils文件夹下新建request.js
  • request.js
import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'

const service = axios.create({
  baseURL: '/admin/', // url = base url + request url
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    config.headers['Accept'] = 'application/json'

    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code === 1) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    if (error.response && error.response.status !== 400 && error.response.status !== 401 && error.response.status !== 409) {
      ElMessage({
        message: error.response && error.response.data && error.response.data.message || error.message,
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
    }
    if (error.response && error.response.status === 401) {
      ElMessage({
        message: '登录已经失效!',
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
      setTimeout(removeToken(), 2000)
      setTimeout(router.push('/login'), 1000);
    }
    if (error.response && error.response.status === 400) {
      ElMessage({
        message: error.response.data.message,
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
    }
    return Promise.reject(error)
  }
)

export default service

状态管理vuex

  1. 在src目录下新建store文件夹
  2. store文件夹下新建index.js, getters.js,以及modules文件夹
  • index.js
import { createStore } from 'vuex'

import getters from './getters'
// 导入模块
const moduleFiles = import.meta.globEager('./modules/*.js')

var modules = {}

for (const path in moduleFiles) {
  const moduleName = path.replace(/^\.\/(.*)\.\w+$/, '$1').split('/')[1]
  modules[moduleName] = moduleFiles[path].default
}

export default createStore({
  modules,
  getters
})
  • getters.js
const getters = {
  token: (state) => state.user.token,
  name: (state) => state.user.name,
  avatar: (state) => state.user.avatar,
};

export default getters;

修改src/main.js,使用状态管理

import { createApp } from "vue";
import App from "@/App.vue";
import router from "@/router";
import store from "@/store";
import installElementPlus from "@/plugins/element";

import "@/styles/index.scss";

const app = createApp(App);

installElementPlus(app);

app.use(router).use(store).mount("#app");

码云地址: https://gitee.com/charming-cheng/vite-element-plus-admin

推荐阅读更多精彩内容