1.创建 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)}})})
}
2.在main.js 中进行全局设置
import Vue from 'vue'
import { myRequest } from './util/api.js'
Vue.prototype.$myRuquest = myRequest //保存在 VUE 的原型中
3.接口调用结果
onLoad() {this.getSwipers()
},
methods: {// 获取轮播图的数据async getSwipers () {const res = await this.$myRuquest({url: '/api/getlunbo'})this.swipers = res.data.message // 过去接口调用后的数据},
}