有这样一个简单需求demo,封装接口请求,点击按钮发送请求,获取接口返回的三张图片
1.先在uniapp当前项目根目录创建utils/request.js
2.封装uni.request请求后导出
//utils/request.js
function fetch(options){
return new Promise((resolve,reject)=>{
uni.request({
url:options.url,
method:options.method,
data:options.data,
success(res) {
resolve(res)
},
fail(err) {
uni.showToast({
title:'请求异常'
}),
reject(err)
}
})
})
}
export {
fetch
}
3.创建api目录,将项目的所有接口封装在这里导出
//getImgs.js
import {
fetch
} from "../utils/request.js"
export const getIMG = function(data) {
console.log(fetch)
return fetch({
url: 'https://api***/******/******/****'
})
}
4 在对应的页面直接引入api接口调用即可
// pages/index/index.vue
<template>
<view>
我是首页
<view @click="getPhotos">
点击发请求
</view>
<view v-for="(item,index) in list" :key="index" >
<image :src="item.image_src" mode="scaleToFill"></image>
</view>
</view>
</template>
<script>
//引入封装的api请求
import {getIMG} from '../../apis/getImgs.js'
export default {
data() {
return {
list: []
}
},
methods: {
getPhotos() {
this.getIMG()
// uni.request({
// url: 'https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata',
// success:(res) => {
// console.log(res.data.message)
// this.list = res.data.message
// }
// })
},
//发起请求获取后端返回的数据(三张图片)
async getIMG(){
console.log('页面开始发请求')
const res = await getIMG()
console.log(res)
this.list = res.data.message
}
}
}
</script>
思路参考来自B站