uniapp封装公共请求typescript版(vue2)
第一步:新建文件夹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' //登录接口 export const login = (data: object | any)=>request('/corp_auth/admin_login', 'POST', data) // 首页获取商品列表
export const getList =(data: object | any)=>request('/goods/get_all_goods_by_collieryid', 'GET', data)
首页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) }) },
再忙也别忘记学习