uniapp中封装请求

  1. 在utils中创建request.js文件
const $request = (url, data, method = 'POST', headers = "application/json;") => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '数据加载中',
			icon: 'loading',
			mask: true
		});
		uni.request({
			url: 'http://192.168.0.101:9096/' + url,
			method: method,
			data: data,
			header: {
				'Content-Type': headers
			},
			success(res) {
				resolve(res)
				uni.hideLoading(); //关闭loading
			},
			fail(error) {
				reject(error);
				// throw new Error(error);
				uni.hideLoading(); //关闭loading
			},
			complete() {
				uni.hideLoading(); //关闭loading
			}
		})
	})
}
//get请求
const $get = (url, data) => {
	return $request(url, data, 'GET')
}
//post请求
const $post = (url, data) => {
	return $request(url, data, 'POST')
}
//给uniapp原生的requset赋值
//记得要在mian.js中引用
uni.$request = $request
uni.$get = $get
uni.$post = $post
  1. 在mian.js中引用request文件
import '@/utils/request.js'
  1. 再创建一个存储接口的文件 再度封装接口
export const fllistApi = (data)=>{
	return uni.$post('url路径',data)
}
  1. 在组件中引入Api 然后调用
	import {fllistApi} from '@/utils/test.js'
	created() {
		this.getlist()
	},
	methods:{
		async getlist(){
				let data = {}
				const res = await fllistApi(data)
				console.log(res)
			}
		}
	



你可能感兴趣的:(uni-app,javascript,前端)