当前位置:   article > 正文

uniapp+vue3,对请求的简单封装配置以及使用_uniapp vue3 请求封装

uniapp vue3 请求封装

请求封装

const BASE_URL = 'http://localhost:8888';

const http = ({
	url,
	data = {},
	method = 'get',
	header = {},
}) => {
	let token = uni.getStorageSync('token') || '';
	if (!url) return;
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + url,
			method,
			data,
			header: {
				token,
				...header
			},
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}
export default http;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

main.js配置

import App from './App';
//引入封装的js文件
import http from '@/utils/http.js'

// #ifdef VUE3
import {
	createSSRApp
} from 'vue';

export function createApp() {
	const app = createSSRApp(App);
	//配置全局属性
	app.config.globalProperties.$http=http
	return {
		app
	}
}
// #endif

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

在xxx.vue中的应用

<script>
	import {
		onMounted,
		getCurrentInstance
	} from "vue";
	export default {
	
		setup() {
			const {
				proxy
			} = getCurrentInstance();
			onMounted(() => {
			
				proxy.$http({
					url: 'xxx',
					data: {	
					},
					method: ''
				}).then(res => {

				})
			})
		}
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/318498
推荐阅读