高级前端-axios

Axios源码分析

简单源码实现参考:https://jframesea.coding.net/public/interview/Interview/git/files/master/javascript/axios.js

请求API化

1. api不要出现在视图层,不然的话修改起来会很麻烦

2. 建立一个api目录,然后根据业务模块划分api

3. 使用 module.method的方式实现调用api,例子:apiModule.user.login()、apiModule.sku.getList()

Axios的二次封装,防止重复提交请求

// 这里的server是axios的一个实例,里面加载了基础配置和拦截器
import server from './server'
function MyServer() {
  this.server = server
  this.nowHandle = null
}

MyServer.prototype.v = function (vueDom) {
  this.nowHandle = vueDom
}

MyServer.prototype.parseRouter = function (name, api) {
  this[name] = {}
  Object.keys(api).forEach(apiName => {
    this[name][apiName] = this.sendMsg.bind(this, name, apiName, api[apiName])
    this[name][apiName].state = 'ready'
  })
}

// 开发轮子是为了提供遍历,同时也要提供给使用轮子的人以扩展性
MyServer.prototype.sendMsg = function (moduleName, apiName, url, config) {
  var config = config || {}
  var method = config.method || 'get'
  var data = config.data || {}
  var params = data
  if (method === 'get') {
    params = {
      params: data
    }
  }
  var bindName = config.bindName || apiName
  var self = this
  // 分模块 =》 效果处理,数据处理
  var before = function (msg) {
    // 效果处理
    // 在这里防止多次请求
    self[moduleName][apiName].state = 'ready'
    return msg
  }

  var defaultFn = function (msg) {
    // 默认数据处理
    // 处理nowHndle
    // this.nowHandle[bindName] = msg
    return msg
  }
  var success = config.success || defaultFn
  if (this[moduleName][apiName].state === 'ready') {
    this[moduleName][apiName].state === 'waiting'
    return this.server[method](url, params).then(before)
  }
}

export default new MyServer()

详细代码参考项目:https://jframesea.coding.net/public/merp-app/merp-app/git/files/master/src/request

猜你喜欢

转载自blog.csdn.net/qq_14855277/article/details/117111753