uniapp封装request请求

忘是亡心i 2022-10-12 15:00 420阅读 0赞

步骤如下:

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

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

思路很简单

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

request.js参考代码如下

  1. // request.js
  2. // 通常可以吧 baseUrl 单独放在一个 js 文件了
  3. const baseUrl = 'http://xxx.xxx.4.xxxx:8093/chemApp'
  4. const request = (options = {}) => {
  5. // 在这里可以对请求头进行一些设置
  6. // 例如:
  7. // options.header = {
  8. // "Content-Type": "application/x-www-form-urlencoded"
  9. // }
  10. return new Promise((resolve, reject) => {
  11. uni.request({
  12. url: baseUrl + options.url || '',
  13. method: options.type || 'GET',
  14. data: options.data || {},
  15. header: options.header || {}
  16. }).then(data => {
  17. let [err, res] = data;
  18. resolve(res);
  19. }).catch(error => {
  20. reject(error)
  21. })
  22. });
  23. }
  24. const get = (url, data, options = {}) => {
  25. options.type = 'GET';
  26. options.data = data;
  27. options.url = url;
  28. return request(options)
  29. }
  30. const post = (url, data, options = {}) => {
  31. options.type = 'POST';
  32. options.data = data;
  33. options.url = url;
  34. return request(options)
  35. }
  36. export default {
  37. request,
  38. get,
  39. post
  40. }

3、在main.js全局注册

  1. import Vue from 'vue'
  2. import App from './App'
  3. import request from 'common/request.js'
  4. Vue.prototype.$request = request
  5. Vue.config.productionTip = false
  6. App.mpType = 'app'
  7. const app = new Vue({
  8. ...App
  9. })
  10. app.$mount()

d41c15df5505c33400d044f16297b564.png

4、页面调用,发起一个get请求

  1. this.$request.get('/caller/getCallers.action', {
  2. "name": "", // 当前页码
  3. "pageBean.page": 1, // 当前页码
  4. "pageBean.rows": 2, // 每页显示数量
  5. "pageBean.pagination": true
  6. }).then(res => {
  7. console.log(res)
  8. })

页面调用的index.vue

  1. <template>
  2. <view>
  3. <uni-list v-for="(item,index) in productList" :key="index">
  4. <uni-list-item :title="item.author_name" :note="item.title"></uni-list-item>
  5. </uni-list>
  6. </view>
  7. </template>
  8. <script>
  9. import uniList from "@/components/uni-list/uni-list.vue"
  10. import uniListItem from "@/components/uni-list-item/uni-list-item.vue"
  11. export default {
  12. components: {
  13. uniList,
  14. uniListItem
  15. },
  16. data() {
  17. return {
  18. productList: [],
  19. };
  20. },
  21. onLoad() {
  22. this.getList();
  23. },
  24. methods: {
  25. getList() {
  26. this.$request.get('/caller/getCallers.action', {
  27. // 传参参数名:参数值,如果没有,就不需要传
  28. // "username": "john",
  29. // "key": this.searchValue
  30. }).then(res => {
  31. // 打印调用成功回调
  32. console.log(res)
  33. this.productList = res;
  34. })
  35. },
  36. }
  37. }
  38. </script>
  39. <style>
  40. </style>

调用成功
4ed2880bd75bc657f71b314d2f0b9b5a.png

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,420人围观)

还没有评论,来说两句吧...

相关阅读