1.使用vue3
2.创建api.js文件,封装网络请求
const BASE_URL = ""// 定义baseurl,便于ip地址更换
export const myRequest = (options)=>{
return new Promise((resolve,reject)=>{
uni.request({
url:BASE_URL+options.url,
method:options.method || 'GET',// 如果没有传,默认为get
data:options.data || {}, // 如果没有传,就为空对象
success:(res)=>{
if(res.data.stauts !==0){
uni.showToast({
title:'获取数据失败'
})
}
resolve(res)
},
fail:(err)=>{
uri.showToast({
title:"获取接口失败"
})
reject(err)
}
})
})
}
3.在main.js中将网络请求方法挂载到全局
import { createApp } from 'vue'
import App from './App.vue'
// 为避免Cannot read properties of undefined (reading 'globalProperties')
// 需要将crateApp和mount分开,将全局绑定内容夹在中间
const app = createApp(App)
import {myRequest} from './util/api.js' // 引入全局函数
app.config.globalProperties.$myRequest = myRequest
app.mount('#app')
4.在vue页面中进行调用
<script>
export default {
data() {
return {
swipes:{}// 轮播图数据
}
},
onLoad() {
this.getSwipes()
},
methods: {
// 获取轮播图数据
async getSwipes(){
console.log("start----")
const res = await this.$myRequest({
url:'',
method:'POST',
data:{
"type":"login",
"code":"888888"
}
})
console.log("end---")
console.log("end"+res)
this.swipes = res
}
}
}
</script>
完成