1.根目录下创建utils/api.js
const BASE_URL = 'http://localhost:8082'
export const myRequest = (options)=>{
return newPromise((resolve, reject)=>{
uni.request({
url: BASE_URL+options.url,
method: options.method || 'GET',
data: optionds.data || {},
success: (res) => {
if (res.data.status !== 0) {
return uni.showToast({
title: '获取数据失败'
})
}
resolve(res)
},
fail: (res)=> {
uni.showToast({
title: '请求接口失败'
})
reject(res)
}
})
})
}
2.在main.js中注册
import Vue from 'vue'
import App from './App'
import { myRequest } from'./util/api.js'
Vue.prototype.$myRequest = myRequest
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
3.使用
<template>
<view class="content">
hello
</view>
</template>
<script>
export default {
data() {
return {
swipers: []
}
},
methods: {
async getSwipers() {
const res = await uni.$myRequest({
url: '/api/getlunbo'
})
this.swipers = res.data.message
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
</style>