一、utils目录下创建一个 api.js 文件
二、api.js封装uni.request() 方法
// 封装 和后端联调接口
const baseURL = "http://192.168.105.42:9090/"; //公共路径 后端给的url
export const myRequest = (options) => {
//加载loading
uni.showLoading({
title:'加载中'
})
return new Promise((resolve, reject) => {
uni.request({
// 开发者服务器接口地址(请求服务器地址 + 具体接口名)
url: baseURL + options.url,
// 请求方式(若不传,则默认为 GET )
method: options.method || 'GET',
// 请求参数(若不传,则默认为 {} )
data: options.data || {},
// 请求成功
success: (res) => {
// 此判断可根据自己需要更改
if (res.data.status !== 1) {
return uni.showToast({
title: '获取数据成功!'
})
}
resolve(res)
},
// 请求失败
fail: (err) => {
uni.showToast({
title: '请求接口失败!'
})
reject(err)
},
//请求结束之后,执行的回调函数(成功或失败都会执行)
complete() {
//隐藏loading
uni.hideLoading()
}
})
})
}
三、main.js 项目入口文件中引入方法,挂载到全局使用
//引入公共接口
import {myRequest} from '@/utils/api.js'
//挂载全局
Vue.prototype.$myRequest = myRequest
四、页面调用
methods: {
integral() {
this.params = {
beginDate: "2020-04-01",
endDate: "2020-04-30"
}
this.$myRequest({
url: 'api/Task/StatisticsOfficialTaskCount',
data: this.params,
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
}
onLoad() {
this.integral();
}