uni-app 网络请求封装并挂载到全局

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>

完成

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值