uni-app封装request请求

在上一篇文章里面,写到使用uni.request请求的方法
https://www.jianshu.com/p/bc62c9e1beed

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请求?步骤很简单,且听我一一道来。

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

步骤如下:

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

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

思路很简单

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

request.js参考代码如下

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全局注册
import request from 'common/request.js'
Vue.prototype.$request = request

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

页面调用的index.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>

成功显示

好了,完结,散花,准备睡觉!!
各位路过的小哥哥,小姐姐,喜欢的就点个赞呗。

欢迎关注【编程微刊】公众号,回复【领取资源】,500G编程学习资源干货免费送。

  • 29
    点赞
  • 132
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值