uniapp封装api

和写普通vue项目一样,单独创建一个api文件夹方便管理。

创建两个.js文件,api.js文件封装请求方法,index.js文件管理所有api接口,若是大项目,创建文件夹进行分类。
在这里插入图片描述

api.js文件内容:

const api = ({
    
    url,method = 'get',data = ''}) => {
    
    
	let URL = "http://xxx" //后台接口地址
	return new Promise((resolve, reject) => {
    
    
		uni.showLoading({
    
    
			title: '加载中',
		})
		uni.request({
    
    
			url: URL + url,
			method,
			data,
			success: res => {
    
    
				uni.hideLoading()
				resolve(res.data)
			}
		})
	})
}
export default api

index.js文件内容:

import api from "./api.js"  //导入封装的请求文件

//要获取的随机集合数量
export const randomList = (count) => {
    
    
	return api({
    
    
		url: '/xcx/test',
		method:'get',
		data: count
	}).then(res => {
    
    
		return res
	})
}

在需要的文件中调用接口

import {
    
    randomList} from '../../api/index.js'

async mounted() {
    
    
	let res = await randomList({
    
    count: 10})
	this.records = res
	this.text = this.records[this.count].content
	this.playQues()
},

猜你喜欢

转载自blog.csdn.net/2201_75499330/article/details/131721402