uniapp如何封装request请求

广告:宝塔Linux面板高效运维的服务器管理软件 点击【 https://www.bt.cn/p/uNLv1L 】立即购买

uniapp如何封装request请求

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

本教程操作环境:windows7系统、uni-app2.5.1版本、thinkpad t480电脑。

推荐(免费):uni-app开发教程

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

<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>
登录后复制

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

以上就是uniapp如何封装request请求的详细内容,更多请关注9543建站博客其它相关文章!

广告:SSL证书一年128.66元起,点击购买~~~

9543建站博客
一个专注于网站开发、微信开发的技术类纯净博客。

作者头像
admin创始人

肥猫,知名SEO博客站长,14年SEO经验。

上一篇:jquery实现点击加一个数字
下一篇:vue和js怎么传递参数

发表评论

关闭广告
关闭广告