uniapp 前端批量注册接口

问题分析:

在项目中,每次使用接口都需要引入,略显麻烦,如果能够批量将所有请求接口的方法都挂载到 Vue 原型上,那么就可以很方便的通过以下方式 this.$apis.getUserInfo(this.params)this.$apis.getCommentList(this.params) 调用接口。

项目目录结构
│  App.vue
│  main.js
│
├─pages
│  ├─login
│  │  │  login.vue
│  │
│  ├─index
│  │  │  index.vue
│  │
│  ├─map
│  │      map.vue
│  │
│  ├─my
│     │  my.vue
│     │
│     ├─components
│           Header.vue
│  
├─services
   │  http.js
   │  index.js
   │
   └─api
           login.js   
           home.js
           map.js
           my.js

一、封装请求库
/* services/http.js */

// 基础路径
export const BASE_URL = 'http://xxx/api/' 

export default function $http(options) {
	return new Promise((resolve, reject) => {
        // 是否显示加载中状态
		if (typeof options.loadingTips !== 'undefined') {
			uni.showLoading({ title: options.loadingTips })
		}
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			header: {
            	// url 是授权接口时不需要 token,其他请求 url 通过本地存储获取 token
				Authorization: options.url === 'auth/auth-getToken' ? '' : uni.getStorageSync(
			'Authorization'),
				'content-type': options.contentType || 'application/json'
			},
			data: options.data,
			success: function(resp) {
				if (resp.statusCode === 200) {
					resolve(resp.data)
				} else {
					if (resp.data.status === 401) {
						uni.clearStorageSync()
						uni.redirectTo({ url: '/pages/login/login?msg=用户验签已失效' })
					}
					uni.showToast({
						icon: 'none',
						title: resp.data.msg
					})
					reject(resp.data.msg)
				}
			},
			fail: err => {
				reject(err)
				uni.showToast({
					icon: 'none',
					title: '服务器异常'
				})
			},
			complete() {
				if (typeof options.loadingTips !== 'undefined') {
					uni.hideLoading()
				}
			}
		})

	})
}
二、定义接口(仅举例其中两个)
/* services/api/login.js */
import $http from '../http.js'

/**
 * 获取token
 */
export const getToken = data => {
	return $http({
		url: 'xxx-auth/auth-getToken',
		method: 'get',
		data,
		contentType: 'application/x-www-form-urlencoded',
	})
}

/**
 * 获取用户基本信息
 */
export const getUserInfo = () => {
	return $http({
		url: 'xxx-auth/get-user-info',
		method: 'get',
		contentType: 'application/x-www-form-urlencoded',
	})
}
/* services/api/home.js */
import $http from '../http.js'

/**
 * 获取评论列表
 */
export const getCommentList = data => {
	return $http({
		url: 'app/comment/list',
		method: 'get',
		data,
		loadingTips: '拼命加载中...',
		contentType: 'application/x-www-form-urlencoded',
	})
}

/**
 * 通过 id 查询评论详情
 */
export const getCommentDetailById = id => {
	return $http({
		url: `app/xxx/findById/${id}`,
		method: 'get',
	})
}
三、借助 require.context 批量导出文件
/* services/index.js */

// 批量导出文件
const requireApi = require.context(
	// api 接口目录的相对路径
	'./api',
	// 是否查询子目录
	false,
	// 查询文件的后缀
	/.js$/
)

let module = {}
requireApi.keys().forEach(key => {
	Object.assign(module, requireApi(key))
})

export default module
四、全局挂载
/* main.js */
import Vue from 'vue'
import App from './App'
import apis from './services'

// 挂载至 Vue 原型上
Vue.prototype.$apis = apis
Vue.config.productionTip = false
App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()
五、使用接口
<!-- pages/index/index.vue -->
<template>
	<view class="index">
		<!-- ... -->		
	</view>
</template>

<script>
export default {
	onShow() {
		this.getCommentList()
	},
	data() {
		return {
			commentList: [],
			params: {
				pageNo: 1,
				pageSize: 10
			}
		}
	},
	methods: {
        // 获取评论列表
		async getCommentList() {
			const { data } = await this.$apis.getCommentList(this.params)
			this.commentList = data
		}
	}
}
</script>

<style lang="scss" scoped>
</style>
Logo

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

更多推荐