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>
本文档展示了如何在uni-app中创建并全局挂载一个名为`myRequest`的网络请求方法,用于统一处理接口调用。首先在根目录下创建`util`文件夹,并在其中创建`api.js`,定义请求基础URL和请求函数。然后在`main.js`中导入并挂载到Vue实例上,使得在所有组件中都能通过`this.$myRequest`调用。最后,在`index.vue`中展示了一个例子,演示如何使用`myRequest`获取轮播图数据。
2499

被折叠的 条评论
为什么被折叠?



