vue中二次封装axios并统一处理loading

关于vue中统一处理axios
每次在开发项目的时候都是需要统一处理请求的,我的项目中使用的是 axios
先在项目中引入 axios

npm: npm install axios
bower:bower install axios
yarn:yarn add axios

首页在我们项目的 utils 文件下创建一个 request 文件夹,然后在 request 文件下创建两个文件 index.js 跟 request.js

在这里插入图片描述
在 request.js 文件中

// request.js
import axios from 'axios' // 引入已经安装好的 axios
import { Toast } from 'vant' // 这里是引入的 vant 中的loading http://vant-contrib.gitee.io/vant/#/zh-CN

// 初次加载loading
const getLoading = () => {
  Toast.loading({
    forbidClick: true,
    message: '加载中...',
    duration: 0
  })
}

// 去除loading
const removeLoading = () => {
  Toast.clear()
}

// loadingNum 监听请求次数当并调用 getLoading 方法
let loadingNum = 0
const severaLmergeLoading = () => {
  if (loadingNum === 0) {
    getLoading()
  }
  loadingNum += 1
}

// 当所有请求结束后,去除整个loading
const endLoading = () => {
  loadingNum--
  if (loadingNum <= 0) {
    loadingNum = 0
    removeLoading()
  }
}

// 创建 axios 实列
const service = axios.create({
	baseURL: 'xxxx', // 地址
	// `timeout` 指定请求超时的毫秒数。
  	// 如果请求时间超过 `timeout` 的值,则请求会被中断
  	timeout: 5000, // 默认值是 `0` (永不超时)
})

// 请求拦截器
service.interceptors.request.use(
	config => {
		// 是否需要 loading
		if (config.hideloading) {
	      severaLmergeLoading()
	    }
		config.headers = {
			// 自定义的一些操作,比如传 token 或者 Content-Type
		}
		return config
	},
	err => {
		// 错误抛出
		endLoading()
		return Promise.reject(err)
	}
)

// 响应拦截器
service.interceptors.response.use(
	response => {
		endLoading()
		// 根据返回的做统一处理
		const res = response.data
		// 这里的 code 根据实际项目中的需求来,以下只是示列
		// 错误
		if(res.code === 0) {
			.....
			return Promise.reject(new Error('出错了'))
		}
		// 成功
		if(res.code === 1) {
			.....
			return Promise.resolve(res)
		}
	},
	err => {
		endLoading()
		// 错误抛出
		return Promise.reject(err)
	}
)

在到 utils -> request -> index.js 文件里

// index.js 文件
// 这里 get 跟 post 分了两个写可以合成一个
// 根据自己实际项目中情况添加需要的自定义参数
import request from './request'

/**
 * get 请求
 * @param {*} url api
 * @param {*} params 参数
 * @param {*} hideloading loading 动画
 * @returns 
 */
export const getAction = (url, params, hideloading = false) => {
  return request({
    url,
    method: 'get',
    params,
    hideloading
  })
}

/**
 * post 请求
 * @param {*} url api
 * @param {*} data 参数
 * @param {*} hideloading loading 动画
 * @returns 
 */
export const postAction = (url, data, hideloading = false) => {
  return request({
    url,
    method: 'post',
    data,
    hideloading
  })
}

最后在我们的根目录下创建一个 api 文件夹来同统一管理api
在这里插入图片描述

// api -> index.js
import { getAction, postAction } from '@/utils/request'

// 项目中的 api
export const getData = (e) => {
   return getAction('xxx/xxxx', e, true)
}

最后的最后就可以在使用的地方尽情愉快的使用啦

import { getData } from '@/api'

export default {
	  mounted() {
	    this.queryList()
	  },
	methods: {
		async queryList() {
			// const data = { ... } // 自定义参数
			// getData().then(res => {
			//		console.log(res)
			// })
			
			// try {
        	// const res = await getData(data)
        	//	 console.log(res)
		    // } catch (error) {
		    	// 异常处理
        		// console.log(error)
      		// } finally {
		        // 成功失败都返回
		    // }
		}
	}
}

有问题的地方评论区讨论

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue 3使用TypeScript封装axios并包含loading功能的步骤如下: 1. 首先,安装axios和@types/axios依赖: ``` npm install axios @types/axios ``` 2. 创建一个名为api.ts的文件,用于封装axios请求和loading功能: ```typescript import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; import { reactive } from 'vue'; // 创建一个loading对象,用于控制loading状态 const loading = reactive({ isLoading: false, }); // 创建一个axios实例 const instance = axios.create({ baseURL: 'https://api.example.com', // 设置请求的基础URL timeout: 5000, // 设置请求超时时间 }); // 请求拦截器,在发送请求之前执行 instance.interceptors.request.use( (config: AxiosRequestConfig) => { loading.isLoading = true; // 开启loading状态 return config; }, (error) => { loading.isLoading = false; // 关闭loading状态 return Promise.reject(error); } ); // 响应拦截器,在接收到响应之后执行 instance.interceptors.response.use( (response: AxiosResponse) => { loading.isLoading = false; // 关闭loading状态 return response.data; }, (error) => { loading.isLoading = false; // 关闭loading状态 return Promise.reject(error); } ); // 封装get请求方法 export const get = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => { try { const response = await instance.get<T>(url, config); return response; } catch (error) { throw new Error(error); } }; // 封装post请求方法 export const post = async <T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => { try { const response = await instance.post<T>(url, data, config); return response; } catch (error) { throw new Error(error); } }; export default { loading, }; ``` 3. 在Vue组件使用封装axiosloading功能: ```vue <template> <div> <button @click="fetchData">Fetch Data</button> <div v-if="api.loading.isLoading">Loading...</div> <div v-else>{{ data }}</div> </div> </template> <script> import { ref } from 'vue'; import api from './api'; export default { setup() { const data = ref(''); const fetchData = async () => { try { const response = await api.get<string>('/data'); data.value = response; } catch (error) { console.error(error); } }; return { fetchData, data, ...api, }; }, }; </script> ``` 在上述代码,我们通过`api.ts`文件封装axios的get和post请求方法,并使用`reactive`创建了一个loading对象来控制loading状态。在Vue组件,我们可以直接调用`api.get`或`api.post`方法来发送请求,并通过`api.loading.isLoading`来控制loading的显示与隐藏。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

内是雾都

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值