uni-app 请求二次封装及挂载全局

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值