vue3--axios 使用

1.官网-安装

http://www.axios-js.com/zh-cn/docs/

npm install axios

2.统一封装类,新建src/http/index.ts

import axios from 'axios'
import { ElLoading } from 'element-plus'
import { ElMessage } from 'element-plus'
interface IResponseData<T> {
    code: number,
    message: string,
    data: T
}
let loading:any;
class Http {
    myAxios: any;
    constructor(config: any) {
        this.myAxios = axios.create(config);
        // 添加请求拦截器
        this.myAxios.interceptors.request.use(function (config:any) {
            //显示loading层
             loading = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)',
              })
            
            return config;
        }, function (error:any) {
           // 对请求错误做些什么
           loading.close();
            return Promise.reject(error);
        });
        // 添加响应拦截器
        this.myAxios.interceptors.response.use(function (response:any) { 
            //关闭loading层
            loading.close();
            const {code,msg,data} = response.data

           if(code === 0){
             return data;
           } else if (code == undefined){
            return response;
           } else if(code != 0){
             ElMessage.error(msg)
             return Promise.reject(msg);
           }

            
        }, function (error:any) {
            // 对响应错误做点什么  
            loading.close();       
            return Promise.reject(error);
        });
    }
    get<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
        return this.myAxios.get(url, { params, ...data });
    }

    post<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
        return this.myAxios.post(url, params, data);
    }

    put<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
        return this.myAxios.put(url, params, data);
    }

    delete<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
        return this.myAxios.delete(url, { params, ...data });
    }

}
const config = {
    baseURL: '',
    timeout: 30 * 1000,
    withCredentials: true,
}

export default new Http(config);
 

3..Proxy配置

在vite.config.ts 文件中

server: {

    port: 5000, // 你需要定义的端口号

    proxy: {
      "/api": {
        target: "Api地址",
        changeOrigin: true,
      
      },
    
    },
 },

4.使用方式

import http from "@/http/index";

onMounted(()=>{

 http.get(
        "/api/products"
      )
      .then((res: any) => {

        tableData.value = res.data;

      })
      .catch((err: any) => {
        console.log(err);
      });

})
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值