HbuilderX数据请求TS封装升级版

1、在src目录上创建util目录然后创建request.ts文件

// https://x.dscmall.cn/api/goods/type_list?page=1&size=10&type=is_best


// 通用的url路径
let baseURl = "https://x.dscmall.cn/api"
// 需要拦截的api名称,如uni.addInterceptor('request',OBJECt),将拦截uni.request()

// 拦截器
const interceptorOptions = {
	// invoke拦截前触发
	invoke(options : UniApp.RequestOptions) {
		options.url = baseURl + options.url
		// timeout请求时间
		options.timeout = 10000
		// 添加请求头
		options.header = {
			...options.header
		}

		// 添加token,token登录成功之后存放到状态管理中
		const token = 'this is token'
		if (token) {
			options.header['token'] = token
		}
	}
}
uni.addInterceptor('request', interceptorOptions)

// 封装请求,使用Promise形式,之后就可以使用async await
export const requestApi = (options : UniApp.RequestOptions) => {
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			success: (res) => {
				if (res.statusCode == 200) {
					resolve(res.data)
				} else {
					uni.showToast({
						"title": "请求失败",
						duration: 2000
					})
					reject(res)
				}
			},
			fail: (err) => {
				uni.showToast({
					"title": "请求失败",
					duration: 2000
				})
				reject(err)
			}
		})
	})
}

// options={
// 	url:"",
// 	method:"",
// 	data:{},
// 	header:{}
// }
// 等价于
// {
// 	...options
// }

2、在src目录下创建api目录用于请求接口,下面创建home.ts文件

// 引入封装的请求数据模块
import { requestApi } from "../utils/request"
// 导出请求数据的方法
// 接口地址https://x.dscmall.cn/api/goods/type_list
// 请求的方式get
// 参数page=1&size=10&type=is_best

// 定于参数接口
// interface IHomeList {
// 	page : number | string,
// 	size : number | string,
// 	type : string
// }

// 定义参数类型
type THomeList = {
	page : number | string,
	size : number | string,
	type : string
}

export const HomeListApi = (data : THomeList) => {
	return requestApi({
		url: "/goods/type_list",
		method: "GET",
		data
	})
}

3、在所需请求数据的页面调用接口

 4、渲染数据

  • 25
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
UniApp是一个基于Vue.js的跨平台开发框架,可以同时开发iOS、Android、H5等多个平台的应用。Vue 3是Vue.js的最新版本,带来了许多新特性和改进。在UniApp中使用Vue 3和TypeScript来封装请求可以按照以下步骤进行: 1. 安装依赖:在UniApp项目中,首先需要安装axios库和@types/axios库,用于发送HTTP请求和提供TypeScript类型定义。 ```bash npm install axios @types/axios ``` 2. 创建请求封装文件:在项目的`src`目录下创建一个`api`文件夹,并在该文件夹下创建一个`request.ts`文件,用于封装请求相关的代码。 ```typescript import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; // 创建axios实例 const instance = axios.create({ baseURL: 'http://api.example.com', // 设置请求的基础URL timeout: 5000, // 设置请求超时时间 }); // 请求拦截器 instance.interceptors.request.use( (config: AxiosRequestConfig) => { // 在发送请求之前做一些处理,例如添加token等 return config; }, (error) => { // 处理请求错误 return Promise.reject(error); } ); // 响应拦截器 instance.interceptors.response.use( (response: AxiosResponse) => { // 对响应数据进行处理,例如统一处理错误码等 return response.data; }, (error) => { // 处理响应错误 return Promise.reject(error); } ); // 封装GET请求 export function get(url: string, params?: any): Promise<any> { return instance.get(url, { params }); } // 封装POST请求 export function post(url: string, data?: any): Promise<any> { return instance.post(url, data); } // 其他请求方法封装,例如PUT、DELETE等 ``` 3. 使用请求封装:在需要发送请求的地方,引入`request.ts`文件,并调用相应的请求方法。 ```typescript import { get, post } from '@/api/request'; // 发送GET请求 get('/user/info', { id: 1 }) .then((response) => { console.log(response); }) .catch((error) => { console.error(error); }); // 发送POST请求 post('/user/login', { username: 'admin', password: '123456' }) .then((response) => { console.log(response); }) .catch((error) => { console.error(error); }); // 其他请求方法的使用,例如PUT、DELETE等 ``` 以上就是在UniApp中使用Vue 3和TypeScript封装请求的基本步骤。你可以根据实际需求进行进一步的封装和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞不起来的飞机耶耶耶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值