1.在根目录下创建util目录。
2.在util目录下新建一个api.js,如下:
const BASE_URL = 'http://127.0.0.1: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 !== 0){
uni.showToast({
title: "获取数据失败"
})
}
resolve(res)
},
fail: err =>{
uni.showToast({
title: "请求接口失败"
})
reject(err)
}
})
})
}
3.全局挂载
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()
4.调用
index.vue:
<template>
<view class="content">
</view>
</template>
<script>
export default {
data() {
return {
swipers: []
}
},
onLoad() {
this.getSwiper();
},
methods: {
async getSwiper() {
const res = await this.$myRequest({
url: '/api/getlunbo',
})
this.swipers = res.data.message
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>