这里通过Promise处理异步操作。
封装uni.request()接口的 util/api.js文件:
// 二次封装请求接口
const BASE_URL = 'http://localhost:8082'
export const myRequest = (options) => {
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + options.url,
method: options.method || 'GET',
data: options.data || {},
success: (res) => {
if(res.data.status !== 0){
return uni.showToast()({
title: '获取数据失败'
})
}
resolve(res)
},
fail: (err) => {
uni.showToast()({
title: '请求接口失败'
})
reject(err)
}
})
})
}
然后在main.js文件内进行导入和全局挂载:
import { myRequest } from './util/api.js'
Vue.prototype.$myRequest = myRequest
使用:
async getData(){
const res = await this.$myRequest({
url: '/api/test'
})
conso le.log(res.data)
}
这里是通过这个$myRequest进行访问接口,并获取数据。
options
正常vue页面中,在onLoad()获取,uni-app文档中有
onLoad: function (option) { //option为object类型,会序列化上个页面传递的参数
console.log(option.id); //打印出上个页面传递的参数。
console.log(option.name); //打印出上个页面传递的参数。
}