uni-app封裝$myRequest 方法並掛載到全局(黑馬商城)


封裝:

// 新建目錄util  目錄下api.js
const BASE_URL = 'http://localhost:8080';

export const myRequest = (options) => {
    return new Promise((resolve,reject)=>{
        uni.request({
            url:BASE_URL+options.url,
            method:options.method || "GET",
            data:options.data || {},
            success:(res)=>{
                if(res.data.status !== 0){
                    return uni.showToast({
                        title:"獲取數據失敗"
                    })
                }
                resove(res)
            },
            fail:(err)=>{
                return uni.showToast({
                    title:"請求接口失敗"
                })
                reject(err)
            }
        })
    })
}

// myRequest({
//     url:'/api/getlunbo',
//     method:"POST",
//     data:{
        
//     },
// })

幾乎每個頁面都會使用,則通過入口文件main.js引入

// main.js
import Vue from 'vue' import App from './App' import {myRequest} from './util/api.js' //引入 Vue.prototype.$myRequest = myRequest //通過Vue.prototype掛載至全局 Vue.config.productionTip = false App.mpType = 'app' const app = new Vue({ ...App }) app.$mount()

使用:

methods: {
            //獲取輪播圖數據
       (1)// getSwipers(){
            //     uni.request({
            //         url:'../../common/util.json',
            //         success:res=>{//             this.swiper= res.data.message
            //         }
            //     })
            // },
    (3)
async getSwipers (){ const res = await this.$myRequest({ url:'/api/getlunbo' }) this.swiper = res.data.message }, (2)// getSwipers (){ // this.$myRequest({ // url:"/api/getlunbo" // }) //返回promise函數,可改為以上方法 通過await async進行修飾 // } }

 


免責聲明!

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



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