uni-app网络请求
uni-app题拱了uni.requet()方法,发起网络请求
uni.request({
url: 'https://wwww.xxxx.cn/api/home/list', //仅为示例,并非真实接口地址。
data: {
text: 'uni.request'
},
header: {
'custom-header': 'header' //自定义请求头信息
},
success: (res) => {
console.log(res.data);
}
});
uni.request请求的封装
src文件夹下创建utils文件夹,再创建request.ts文件,用于封装请求,使用promise封装
interface requestInt {
url: string,
method: 'GET' | 'POST',
data: string | object | ArrayBuffer,
options?: any,
}
class HttpRequest {
request = (params: requestInt) => {
let { url, method, data, options } = params
uni.showLoading({
title: '加载中...',
mask: true
});
return new Promise<any>((resolve, reject) => {
uni.request({
url: `${import.meta.env.VITE_BASE_URL}${url}`,
method,
data,
header: {},
success: (res: any) => {
uni.hideLoading();
switch (res.statusCode) {
case 200:
resolve(res)
break;
default:
uni.showModal({
title: '温馨提示',
content: '未知异常,请稍后在试!',
showCancel: false,
});
reject(res)
}
console.log(`${method}请求类型++++++++++`);
},
fail: (err: any) => {
uni.hideLoading();
uni.showModal({
title: '温馨提示',
content: '接口异常,请稍后在试!',
showCancel: false,
});
console.log(err, '接口fail++++++++++++');
reject(err)
}
})
})
}
// get请求
get(url = '', data = {}, options = {}) {
return this.request({
url,
method: "GET",
data,
...options
});
}
// post请求
post(url = '', data = {}, options = {}) {
return this.request({
url,
method: 'POST',
data,
...options
});
}
}
export default new HttpRequest();
在src文件夹下创建api文件夹,将前端所有的请求文件都放在里面文章来源:https://www.toymoban.com/news/detail-523707.html
例如在api文件夹下创建home.ts文件 文章来源地址https://www.toymoban.com/news/detail-523707.html
import request from '@/utils/request'
export const frontpage = (data = {}) => {
return request.get('frontpage', data)
}
在vue文件中使用
//home.vue
<template>
<view class="content"></view>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { frontpage } from '@/api/home'
import type { Vaccine } from '@/types/decl-type'
let vaccine = ref<Vaccine[]>([])
onMounted(() => {
homeData()
})
const homeData = async () => {
const res: any = await frontpage()
console.log(res, '首页数据+++++++++')
vaccine.value = res.data.data[0].vaccine
}
</script>
<style lang="scss"></style>
到了这里,关于uniapp uni.requet()二次封装ts版的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!