首页 > 移动平台 > 详细

axios 使用

时间:2021-06-02 15:22:56      阅读:21      评论:0      收藏:0      [点我收藏+]

npm install axios -s  安装

一般使用的时候会根据项目需求做扩展处理方便使用,以下是最近的项目处理axios的方式

1.  axios.default 的通用默认配置,及封装可扩展的方法

2. axios.all 和 axios.spread  封装处理高并发的请求

3. axios.CancelToken 和 axios.Cancel 常用的方法处理

4. requestInterceptor 和 responseInterceptor 请求拦截通用处理

5. 封装处理多台服务的请求实例集合

例子:

function getInstances (conf) { // 封装实例
  let result = {} // 实例集合
  let domains = {} // 接口请求地址
  axios.defaults = merge(axios.defaults, conf) // 合并配置
  result.$http = axios
  for (let key in domains) {
        key = key.trim()
        let instance = axios.create(domains[key])
        let domainName = `\$${key}`
        instance.all = (promises) => return axios.all(promises)
        instance.spread = (cb) => return axios.spread(cb)
        instance.Cancel = () => return axios.Cancel
        instance.CancelToken = () => return axios.CancelToken
        instance.isCancel = () => return axios.isCancel
        result[domainName] = instance // 添加高并发实例
  }
  return result
}
const http = getInstances(config)  // 调用实例
const HttpPlugin = { // 扩展都Vue实例
  install: (Vue) => {
    if (http === null) {
      Vue.prototype.$http = axios
    } else {
      for (let domainName in http) {
        Vue.prototype[domainName] = http[domainName]
      }
    }
  }
}
 
// 请求拦截根据需求处理,省略。。
 
Vue.use(HttpPlugin) // 使用
 

axios 使用

原文:https://www.cnblogs.com/tanjj/p/14840593.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!