uni-app的uni.request()請求封裝


第一種:常見的直接發起uni.request()請求

        onLoad() {//頁面加載時調用
            this.getSwipers()
        },
        methods: {
            //獲取輪播圖數據
            getSwipers(){
                uni.request({
                    url:"https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata",
                    method:"GET",
                    success: (res) => {
                        console.log(res)
                        if(res.data.meta.status !== 200){//如果請求失敗,不等於200狀態碼
                            return uni.showToast({
                                title:"請求失敗!"
                            })
                        }
                        //數據請求成功
                        this.swipers = res.data.message
                    }
                })
            }
        }

  

 第二種:async修飾函數和await的使用,這個好像是es7的

        onLoad() {//頁面加載時調用
            this.getSwipers()
        },
        methods: {
            //獲取輪播圖數據
            async getSwipers(){
                const res = await uni.request({
                    url:"https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata",
                    method:"GET" //默認是GET,可省
                })
                console.log(res)
            }
        }

  

第三種:es6異步promise封裝這種發起請求接口,跟axios封裝差不多

一個項目有N多個接口,但前面的一段url基本是一致不變的(專業點說也就是前面那一段是域名,域名是不變的+后面一段是變化的,是接口地址)。

這時候我們就可以抽離封裝了api了。

 

api.js
//功能:暴露接口

const BASE_URL = 'https://api-hmugo-web.itheima.net' //域名或選取所有接口不變的那一部分
export const myRequest = (options) => { //暴露一個function:myRequest,使用options接收頁面傳過來的參數
        return new Promise((resolve, reject) => { //異步封裝接口,使用Promise處理異步請求
            uni.request({ //發送請求
                url: BASE_URL + options.url, //接收請求的API
                method: options.method || 'GET', //接收請求的方式,如果不傳默認為GET
                data: options.data || {}, //接收請求的data,不傳默認為空
                success: (res) => { //數據獲取成功
                    if (res.data.meta.status !== 200) { //因為200是返回成功的狀態碼,如果不等於200,則代表獲取失敗,
                        return uni.showToast({
                            title: "數據獲取失敗!"
                        })
                    }
                    resolve(res) //成功,將數據返回
                },
                fail: (err) => { //失敗操作
                    uni.showToast({
                        title: "請求接口失敗!"
                    })
                    reject(err)
                }
            })
        })
    }

/*下面代碼不作用途:僅參照演示,模仿頁面調用函數,將實參傳進myRequest,也就是上面myRequest使用(options)接收。
myRequest({
    url: '/getInfo',
    method: 'POST',
})
*/

在uni-app的main.js中將api.js掛載到全局,讓所有頁面都能接收

import { myRequest } from './utils/api.js'

//掛載到全局,讓所有頁面都能接收
Vue.prototype.$myRequest = myRequest //掛載到Vue的原型上

  頁面調用(index.vue想使用):

        data() {
            return {
                swipers: []
            }
        },
        onLoad() { //頁面加載時調用
            this.getSwipers()
        },
        methods: {
            //獲取輪播圖數據
            async getSwipers() {
                const res = await this.$myRequest({//調用封裝好的API請求函數
                    url:'/api/public/v1/home/swiperdata',//把接口傳過去
                    method:'GET',
                })
                console.log(res)
                this.swipers = res.data.message //保存值
            }
        }

  



作者:似朝朝我心
鏈接:https://www.jianshu.com/p/8276ca362e5c
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
 

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>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM