Vue的axios全局安装

1、cnpm install axios --save
2、全局默认axios:
引入axios
2、全局axios:
在这里插入图片描述
在这里插入图片描述
Vue.prototype.$axios = axios
还要添加一句:
在这里插入图片描述
axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-
urlencoded’;
也就是下面这句:
在这里插入图片描述

Vue 使用 Axios 全局节流防抖的方法有很多,以下是其一种常见的方法: 1. 在 main.js ,引入 lodash 的 throttle 和 debounce 方法 ```javascript import _ from 'lodash' Vue.prototype.$throttle = _.throttle Vue.prototype.$debounce = _.debounce ``` 2. 在 Vue 实例,使用 $throttle 或 $debounce 方法包装 Axios 请求方法 ```javascript import axios from 'axios' export default { methods: { // 使用 $throttle 包装 Axios 请求方法,实现全局节流 async $throttleAxios(url, data, config) { return this.$throttle(async () => { try { const response = await axios.post(url, data, config) return response.data } catch (error) { console.error(error) } }, 1000) }, // 使用 $debounce 包装 Axios 请求方法,实现全局防抖 async $debounceAxios(url, data, config) { return this.$debounce(async () => { try { const response = await axios.post(url, data, config) return response.data } catch (error) { console.error(error) } }, 1000) }, }, } ``` 在上述代码,$throttleAxios 和 $debounceAxios 方法分别使用 $throttle 和 $debounce 方法包装了 Axios 请求方法,实现了全局的节流和防抖。其,$throttleAxios 的节流时间间隔为 1000ms,$debounceAxios 的防抖时间间隔也为 1000ms。 3. 在组件调用全局节流防抖的 Axios 请求方法 ```javascript export default { methods: { async fetchData() { // 调用 $throttleAxios 方法获取数据 const data = await this.$throttleAxios('/api/data', { page: 1 }) // 调用 $debounceAxios 方法保存数据 await this.$debounceAxios('/api/save', data) }, }, } ``` 在组件,通过调用 $throttleAxios 和 $debounceAxios 方法,即可实现全局节流防抖的 Axios 请求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值