美文网首页
vuex+axios封装

vuex+axios封装

作者: 萘小蒽 | 来源:发表于2021-07-20 09:43 被阅读0次

    以一个简单登录为例
    1. 先配置aixos,这里用到了element-ui的提示组件。
    工具模块@/uitl/aixos.js

    /**
     *
     * http配置
     * 
     */
    // 引入axios以及element ui中的loading和message组件
    import Axios from 'axios'
    import store from '../store'
    import router from '../router/router';
    //请求对token的操作
    import { getToken, setToken, removeToken } from '@/util/auth'; 
    import { Loading, Message } from 'element-ui'
    
    let axios = Axios.create({
      timeout: 10000,
      headers: {
        'Content-Type': "application/json;charset=utf-8"
      }
    });
    
    // 超时时间
    if (store.online) axios.defaults.timeout = 13000;
    else axios.defaults.timeout = 0;
    //跨域请求,允许保存cookie
    axios.defaults.withCredentials = true;
    //跨域请求,本地接口测试。
    let ip = 'http://192.168.215.38:9999';
    // Nginx 做转发
    axios.defaults.baseURL = ip;
    let loadinginstace
    let cfg, msg;
    msg = '服务器君开小差了,请稍后再试';
    //HTTPrequest拦截
    axios.interceptors.request.use(config => {
      loadinginstace = Loading.service({
        fullscreen: true
      });
      if (store.getters.token) {
        config.headers['Authorization'] = 'Bearer ' + getToken()// 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      }
      return config
    }, error => {
      return Promise.reject(error)
    })
    //HTTPresponse拦截,根据自己返回的res,需求自作修改.
    axios.interceptors.response.use(
      response => {
        loadinginstace.close();
        const res = response.data
        if (res.code === 1) {
          message(res.msg, 'error')
          return Promise.reject(res)
        }
        return response
      },
      error => {
        loadinginstace.close();
        const res = error.response
        if (res.status === 478 || res.status === 403) {
          message(res.data.msg, 'error')
        } else if (res.status === 400) {
          message(res.data.error_description, 'error')
        } else if (res.status === 202) { //三方未绑定
          this.$router.push({ path: '/' })
        } else if (res.status === 503) {//服务异常
          message(res.data, 'error')
        } else if ((res.status === 401 && res.statusText == 'Unauthorized') || res.data.error == 'invalid_token' || res.data.error == 'unauthorized') {//token失效
          store.dispatch('FedLogOut').then(() => {
            router.push('/login')
          })
        } else {
          message(res.data.message, 'error')
        }
        return Promise.reject(error)
      }
    )
    export function message (text, type) {
      Message({
        message: text,
        type: type,
        duration: 5 * 1000,
        center: true
      })
    }
    export default axios
    

    2. 请求API封装
    已登录接口模块为例 @/api/user.js

    //user.js
    import request from '@/util/axios'
    //接口以及参数已自己项目需求自作修改
    export const loginByUsername = (username, password, code, randomStr) => {
      var grant_type = 'password'
      var scope = 'server'
      return request({
        url: '/auth/oauth/token',
        headers: {
          'Authorization': 'Basic bGltaW46bGltaW4='
        },
        method: 'post',
        params: { username, password, randomStr, code, grant_type, scope, mark: 2 }
      })
    }
    

    3. store目录配置

    下面是我的vuex模块的文件目录,根据项目结构自行修改。

    store
    先看管理登录的配置store/modulses/user.js
    
    import { getToken, setToken, removeToken } from '@/util/auth'
    import { loginByUsername } from '@/api/user'
    const user = {
      state: {
    
      },
      actions: {
        //根据用户名登录
        LoginByUsername ({ commit, state, dispatch }, userInfo) {
          return new Promise((resolve, reject) => {
            loginByUsername(userInfo.username, userInfo.password, userInfo.code, userInfo.redomStr).then(res => {
              const data = res.data;
              setToken(data.access_token)
              resolve(res.data);
            }).catch(() => { })
          })
        }
      }
      
    
    }
    export default user
    

    @/store/index.js

    import Vue from 'vue'
    import Vuex from 'vuex'
    import user from './modules/user'
    
    Vue.use(Vuex)
    const store = new Vuex.Store({
      modules: {
        user
      },
      getters,
    })
    
    export default store
    

    main.js引入store

    import store from './store';
    //省略很多代码
    export function createApp() {
      const app = new Vue({
        router,
        store,
        render: h => h(App)
      })
      return { app, router, store }
    }
    

    相关文章

      网友评论

          本文标题:vuex+axios封装

          本文链接:https://www.haomeiwen.com/subject/vsmvwctx.html