乐趣区

关于uniapp:uniapp封装公共请求typescript版

第一步:新建文件夹 services

第二步:新建文件 request.ts

// 服务器接口地址
 const baseURL:string='http://xxxxxx' 
 // 本地调试接口地址
// const baseURL:string='http://xxxxxx'

// 封装公共申请办法
function request(url:string, method: "GET" | "POST" | undefined,data: object | any){return new Promise(function(resolve, reject){
              let header:any
              if(uni.getStorageSync('token') !== undefined && uni.getStorageSync('token') !== ""){
                header = {
                  'content-type': 'application/json',
                  'X-Auth-Token': uni.getStorageSync('token')
                };
              }else {
                header = {'content-type': 'application/json',};
              }
              uni.request({
                    url: baseURL + url,
                    method: method,
                    data: data,
                    header: header,
                    success(res:any) {console.log(res)
                        uni.hideLoading()
                      if (res.data.code === "200" || res.data.ok) {resolve(res.data);
        
                      } else {
                        // 其余异样
                        uni.showToast({
                            title:res.data.msg,
                            icon:'none'
                        })
                        reject(res.data);
                      }
                    },
                    fail(err) {uni.hideLoading()
                      // 申请失败
                      uni.showToast({
                          title:'无奈连贯到服务器',
                        icon:'none'
                      })
                      reject(err)
                    }
                    
                  })
                  
            })
            
    }


export {request,baseURL}

第三步:新建同级文件 api.ts

import {request} from './request'
// 登录接口
const login = (data: object | any)=>request('/corp_auth/admin_login', 'POST', data)
 // 首页获取商品列表
const getList =(data: object | any)=>request('/goods/get_all_goods_by_collieryid', 'GET', data)

export{
    login,
    getList

}

首页 index.vue 引入须要的接口

<script lang="ts">
    import Vue from 'vue';
    import {getList} from '../../../services/api';
    export default Vue.extend({data() {
            return {list:[],
                pageNow:'',
            }
        },
        onLoad(options) {this.initList(),
               
        },

        onReachBottom() { // 上拉加载
            this.pageNow = this.pageNow + 1
            this.initList()},
        methods: {async initList() { 
                const listRes: any = await getList({pageNow: this.pageNow,})
                this.list = this.list.concat(listRes.payload)
            },
        },

    });
</script>

如果外面有 success 等回调函数,就不能用 async 和 await 的写法,应该用上面这种

initList() {   let that = this
          getList({pageNow: this.pageNow}).then(res => {that.list = that.list.concat(res.data.payload)
               })
               
            },
退出移动版