uniapp.request的簡單封裝和調用

根目錄新建util文件夾,新增api.js文件

  • api.js
/**
 * 接口調用封裝文件
 * 作者:z_d_f
 * 時間:2021/06/25
 * 根據uni.request()做進一步封裝,採用Promise進行優化響應。
 */
const BASE_URL = "https://api.vvhan.com"  // 豆瓣測試地址

if (process.env.NODE_ENV === 'development') {
    // console.log("開發環境");
} else {
    // console.log("生產環境");
}
    
export const httpRequest = options => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: BASE_URL + options.url,
            method: options.method || "GET",// 請求類型,默認爲GET
            data: options.data || {}, // 請求參數,默認空對象
            success: res => {
                // 狀態判斷,根據後臺定義並提示
                console.log(res)
                if (res.data.success) {
                    resolve(res.data.data)
                } else {
                    uni.showToast({
                        title: "獲取數據失敗:"
                    })
                    return
                }
            },
            fail: err => {
                uni.showToast({
                    title: "請求失敗!"
                })
                reject(err)
            }
        })
    })
}

main.js引入

import { httpRequest } from './util/api.js'

// 全局註冊接口調用方法
Vue.prototype.$httpRequest = httpRequest 

界面調用

  • script

<script>
    export default {
        data() {
            return {
                swipers: []
        },
        onLoad() {
            this.getMovieImg()
        },
        methods: {
            async getMovieImg() {
                const res = await this.$http({
                    url: "/api/douban"
                })
                this.swipers = res.data.data.map(r => {
                    return r.info
                })
            }
        }
    }
</script>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章