微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

uniapp请求封装

 

以下为测试接口数据结构  获取轮播图数据

 

 

 

基本用法未封装之前

getSwiper(){
                let that=this;
                uni.request({
                    url:"http://192.168.31.115:8082/api/getlunbo",
                    data:{},
                    method:'GET',
                    dataType:'json',
                    success(res){
                       console.log('ssssss',res); 
                       that.swiperList = res.data.message;
                    }
                })
            },


 

箭头函数省略that=this写法  提取本地域名存储变量


data() {
    return {
          https:'http://192.168.31.115:8082',
          swiperList: [], //轮播图

     }

}

 

onLoad(e) {
     this.getSwiper();
},

methods: {

    getSwiper(){
                uni.request({
                    url:this.https+"/api/getlunbo",
                    data:{},
                    method:'GET',
                    dataType:'json',
                    success:(res)=>{
                       console.log('ssssss',res); 
                       this.swiperList = res.data.message;
                    }
                })
     },
}

全局封装请求方法

utils文件夹api.js文件如下

// const BASE_URL="http://localhost:8082";  //域名抽取
const BASE_URL="http://192.168.31.115:8082";
const HEADER={ 'content-type': 'application/x-www-form-urlencoded' };  //头部
export const myRequest=(options)=>{
    return new Promise((resolve,reject)=>{
        uni.request({
            url:BASE_URL+options.url,
            method:options.method||'GET',
            header: HEADER,
            data:options.data||{},
            dataType: 'json',
            success:(res)=>{
                // if(res.data.status!==0){
                //     return uni.showToast({
                //         title:"获取数据失败"
                //     })
                // }
                resolve(res)
            },
            fail:(err)=>{
                reject(err);
            }
        })
    })
}

main.js

import Vue from 'vue'
import App from './App'
import { myRequest } from './util/api.js'  //引入
 
Vue.prototype.$myRequest=myRequest;    挂载方法到vue全局

Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()
// node ./src/app.js  开启后端服务

 

 

页面


onLoad(e) {
   this.getSwiper();

}



methods: { // 获取轮播图接口信息 async getSwiper() { let res = await this.$myRequest({ url: '/api/getlunbo', methods: "get" }) this.swiperList = res.data.message; },
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐