字节笔记本

2026年2月23日

uni-app 封装 request 请求教程

在上一篇文章里面,写到使用uni.request请求的方法,代码如下:

javascript
getList() {
  uni.request({
    url: "https://unidemo.dcloud.net.cn/api/news",
    method: 'get',
    dataType: 'json',
    success: (res) => {
      console.log(res.data);
      this.productList = res.data;
    },
  });
},

但是实际做项目的时候,会发现每个界面都要重复的写这些,看起来重复又啰嗦,心情就十分的不美丽了。

如果不封装那么我们会面临几个不方便的地方:

  • 请求头每次网络请求都要单独设置
  • 返回数据的正确性判断每次都要重复大量代码
  • 返回数据格式有变化需要修改所有网络请求的地方

那么,该怎么使用uni-app封装一个request请求?步骤很简单,且听我一一道来。

注意:使用的例子,来自于这篇文章的相关的代码,修改封装请求是基于这个文章里面代码。进行相关的修改的。

1、项目下新建common文件夹,再创建request.js文件

2、打开request.js文件,开始写封装的代码

思路很简单:

  • 定义域名:baseUrl
  • 定义方法:api
  • 通过promise异步请求,最后导出方法

request.js参考代码如下:

javascript
const baseUrl = 'https://unidemo.dcloud.net.cn'

const request = (url = '', date = {}, type = 'GET', header = { }) => {
  return new Promise((resolve, reject) => {
    uni.request({
      method: type,
      url: baseUrl + url,
      data: date,
      header: header,
      dataType: 'json',
    }).then((response) => {
      setTimeout(function() {
        uni.hideLoading();
      }, 200);
      let [error, res] = response;
      resolve(res.data);
    }).catch(error => {
      let [err, res] = error;
      reject(err)
    })
  });
}

export default request

3、在main.js全局注册

javascript
import request from 'common/request.js'
Vue.prototype.$request = request

4、页面调用

javascript
this.$request('/api/news', {
  // 传参参数名:参数值,如果没有,就不需要传
}).then(res => {
  // 打印调用成功回调
  console.log(res)
})

页面调用的index.vue完整代码:

vue
<template>
  <view>
    <uni-list v-for="(item,index) in productList" :key="index">
      <uni-list-item :title="item.author_name" :note="item.title"></uni-list-item>
    </uni-list>
  </view>
</template>

<script>
import uniList from "@/components/uni-list/uni-list.vue"
import uniListItem from "@/components/uni-list-item/uni-list-item.vue"

export default {
  components: {
    uniList,
    uniListItem
  },
  data() {
    return {
      productList: [],
    };
  },
  onLoad() {
    this.getList();
  },
  methods: {
    getList() {
      this.$request('/api/news', {
        // 传参参数名:参数值,如果没有,就不需要传
        // "username": "john",
        // "key": this.searchValue
      }).then(res => {
        // 打印调用成功回调
        console.log(res)
        this.productList = res;
      })
    },
  }
}
</script>

<style>
</style>

成功显示数据后,就完成了uni-app request请求的封装。


原文链接: https://cloud.tencent.com/developer/article/1658712

分享: