get request uni 参数_uniapp如何封装request请求

uniapp封装request请求的方法:首先项目下新建common文件夹,再创建【request.js】文件;然后打开【request.js】文件,开始写封装的代码;最后通过promise异步请求,最后导出方法。

本教程操作环境:windows7系统、uni-app2.5.1版本,该方法适用于所有品牌电脑。

uniapp封装request请求的方法:

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

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;

})

},

}

}

相关免费学习推荐:编程视频

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值