和写普通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()
},