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 = data => {
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,
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>