1.首先在根目录新建common/http目录,然后在http中新建两个js如 图

2.http.js代码

import Vue from 'vue'
const request = (params) => {
	// 显示加载数据的提示
	uni.showLoading({
		title: '加载中',
		mask: true
	})
	return new Promise(function(resolve, reject) {
		const baseUrl = Vue.prototype.$baseUrl;
		let token_value=store.state.token;
		uni.request({
			method: params.method,
			data: params.data,
			url:baseUrl + params.url,
			header: {
                    ////此处是token 可不加,如果加了需要配置后端允许跨域
				'token': token_value
			},
			success(res) {
				setTimeout(function() {
					resolve(res)
				}, 500);
			},
			fail(err) {
				reject(err)
			},
			complete() {
				setTimeout(function() {
					uni.hideLoading()
				}, 500);

			}
		})
	})
}
export default request;

3.api.js 存放的是所有的接口

import request from "./http.js"
import Vue from 'vue'
export default {
	//获取app版本
	api_getUpdateApp: function(params) {
		return request({
			method: "POST",
			url: "index/app_fun/getUpdateApp",
			data: params
		});
	},
	///获取首页的功能列表
	api_getFunList:function(params) {
		return request({
			method:"POST",
			url:"api/app_fun/getFunList",
			data:params
		})
	},

}

 3.配置main.js,允许全局使用

import Vue from 'vue'
import App from './App'
import api from 'common/http/api.js'

Vue.prototype.$api = api

 if (process.env.NODE_ENV === 'development') {
 	//开发环境
 	Vue.prototype.$http="http://192.168.0.103/"
 	Vue.prototype.$baseUrl = "http://192.168.0.103/public/index.php/"
 	Vue.prototype.$fileUrl = "http://192.168.0.103/public/"
 } else {
 	//生产环境
	Vue.prototype.$http="https://s.june.com/"
 	Vue.prototype.$baseUrl = "https://s.june.com/public/index.php/"
 	Vue.prototype.$fileUrl = "https://s.june.com/public/" //图片展示域名
 }
App.mpType = 'app'

const app = new Vue({
	...App
})
app.$mount()

4.页面中调用接口

<template>
	<view class="content">

	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello',
			
			}
		},
		onLoad() {
               /* 该接口是在api.js中定义过的 */
			this.$api.api_getUpdateApp({
				user_id:'sdfsdfsd',
				name:'测试'
			}).then(res=>{
				/* 成功的回调 */
			}).catch(err=>{
				/* 失败回调 */
			}).finish(e=>{
				/* 成功或者失败都会执行 */
			})
		},
		methods: {

		}
	}
</script>

<style>

</style>

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐