当前位置:   article > 正文

Vue中封装Axios及统一验证返回结果(Vue3及Vue2都能用)_axios封装直接返回data

axios封装直接返回data

一,下载及安装vue3及axios

1,vue-cli 安装vue3 (默认已会) 官网地址:vue-cli
2,安装axios 官网地址:axios

$ npm install axios
  • 1

二,配置文件

在src文件目录下新建一个文件夹 名为api,在新建的文件夹中新建 4个js文件,本人命名为 api.js、axios.js、config.js、verify.js(此为统一验证js)
在 public中新建config.js 文件 并在 index.html 中引入该文件,做统一配置地址处理
如图所示:文件目录

三,代码

1,public 文件夹中 config.js

((W) => {
    W.configParams = {}
    // 请求的公共地址
    configParams.baseURL = "http://xxxxx:8090/xxxx"; // 自己 
    // configParams.baseURL = "http://xxxxx:8090/xxxx"; // 周 
})(window)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2,public 文件夹中 index.html

<script src="./config.js"></script>
  • 1

3,在 axios.js 中

import axios from 'axios'
// import router from "@/router";
import store from '@/store/index'
// import {
//     Toast
// } from "vant";
const baseURL = configParams.baseURL
const instance = axios.create({
    baseURL: baseURL,
    timeout: 1000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'token': ''
    },
});
// 请求之前拦截
instance.interceptors.request.use(config => {
    // 赋值token 在vuex 中已经定义好
    // config.headers.token = store.state.token
    if (config.method != "get") {
        // 对data参数处理
        let formdata = new FormData();
        Object.keys(config.data).forEach(key => {
            formdata.append(key, config.data[key]);
        })
        config.data = formdata;
    } else {
        config.data = {}
    }
    return config
})
// 请求响应拦截
instance.interceptors.response.use(config => {
    return config
})

export default instance
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

4,config.js

// 每个接口的名字维护 若接口过的 可分文件引入
export default {
    // 查询获取用户信息 
    getUserInfo: {
        url: `/userInfo/getUserInfo`,
        method: 'post'
    },
    // 刷新token 
    refreshUserToken: {
        url: `/userInfo/refreshUserToken`,
        method: 'post'
    },
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

5,api,js 接口数据请求整合

import request from "./axios"
import baseConfig from "./config"
export function API(apikey, param) {
    let apk = baseConfig[apikey]
    if (apk) {
        return request({
            ...apk,
            params: apk.method == "get" ? param : '',
            data: apk.method == "get" ? "" : param
        })
    } else {
        return {
            code: '404',
            desc: `没有找到[${apikey}]对应的请求配置`
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

6,verify,js 请求验证的 可不用自行定夺 请自己编辑如何验证

//import { Toast } from "vant"
export function verify(res) {
    // console.log(res)
    if (res.data.status == 0) {
        // Toast.success("sss")
        return true
    } else {
        //Toast.fail(res.data.msg)
        return false
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

四,在main.js中添加代码

import { createApp } from 'vue'
import { API } from './api/api';
import { verify } from './api/verify';
const Vue = createApp(App);
Vue.config.globalProperties.$HTTP = API;
Vue.config.globalProperties.$verify = verify;
Vue.mount('#app')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

注:Vue3.x不支持 vue2中直接Vue.prototype. H T T P 这种方式来挂载全局对象,如使用 v u e 2 封装可用这种方式,其它文件代码不用动 v u e 3 中使用 V u e . c o n f i g . g l o b a l P r o p e r t i e s . HTTP 这种方式来挂载全局对象,如使用vue2封装可用这种方式,其它文件代码不用动 vue3 中使用 Vue.config.globalProperties. HTTP这种方式来挂载全局对象,如使用vue2封装可用这种方式,其它文件代码不用动vue3中使用Vue.config.globalProperties.HTTP

五,在页面中应用

在需要调用接口的页面中直接使用 例如:在index.vue中应用
注: 引用接口的函数方法 要使用 async await

<template>
  <router-view /> 
</template>

<script> 
export default { 
  data() {
    return {};
  },

  mounted() {
    this.getUserInfo();
  },
  methods: { 
    async getUserInfo(code=123456) {
      let res = await this.$HTTP("getUserInfo", { code: code });
      if (this.$verify(res)) {
        console.log(res.data);
      }
    }, 
  },
};
</script>

<style>
</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

到此结束 有不足或错误的地方 请指出 谢谢
可加Q群联系:805371278

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/427987
推荐阅读
相关标签
  

闽ICP备14008679号