uni-app项目中封装异步请求

为什么要封装?

  • 原生的请求不支持 promise
  • uni-api 的请求不能够方便的添加 请求中 (loading) 效果
  • uni-api 的请求返回值是个数组,不方便数据处理

封装思路:

  • 基于原生的 promise 来封装
  • 挂载到Vue的原型上
  • 通过 this.request 的方式来使用

封装步骤:

  1. 在src目录下新建utils/request.js
// request.js
export default (params) => {
    
    

  // 加载中效果设置
  uni.showLoading({
    
    
    title: "加载中"
  })

  return new Promise((resolve, reject) => {
    
    

    wx.request({
    
    
      ...params,
      success (res) {
    
    
        resolve(res.data);
      },
      fail (err) {
    
    
        reject(err);
      },
      complete () {
    
    
        uni.hideLoading();
      }
    })

  })
}
  1. 挂载
import Vue from 'vue'
import App from './App'
import request from './utils/request' // 1. 引用

Vue.config.productionTip = false

Vue.prototype.request = request // 2. 挂载到vue中

App.mpType = 'app'

const app = new Vue({
    
    
  ...App
})
app.$mount()
  1. 使用
export default {
    
    
  // ...
  async onLoad () {
    
    
    //http://157.122.54.189:9088/image/v3/homepage/vertical?limit=10&order=hot&skip=2
    // this.request({ url: 'http://157.122.54.189:9088/image/v3/homepage/vertical?limit=10&order=hot&skip=2' }).then((res) => {
    
    
    //   console.log(res)
    // })
    const res = await this.request({
    
     url: 'http://157.122.54.189:9088/image/v3/homepage/vertical?limit=10&order=hot&skip=2' })
    console.log(res)
  }
}

猜你喜欢

转载自blog.csdn.net/tyoubinn/article/details/109001183