前言
ajax相信不用过多介绍了,作者坚信可以用配置解决的问题,请勿硬编码,下面话不多说了,来一看看详细的介绍吧。
姊妹篇 jQuery进阶:用最优雅的方式写ajax请求
axios是Vue官方推荐的ajax库, 用来取代vue-resource。更多详细的基础知识可以参考这篇文章://www.jb51.net/article/109444.htm
优点:
- 增加一个ajax接口,只需要在配置文件里多写几行就可以
- 不需要在组件中写axios调用,直接调用api方法,很方便
- 如果接口有调整,只需要修改一下接口配置文件就可以
- 统一管理接口配置
1. content-type配置
// filename: content-type.js
module.exports = {
formData: 'application/x-www-form-urlencoded; charset=UTF-8',
json: 'application/json; charset=UTF-8'
}
2. api 配置
// filename: api-sdk-conf.js
import contentType from './content-type'
export default {
baseURL: 'http://192.168.40.231:30412',
apis: [
{
name: 'login',
path: '/api/security/login?{{id}}',
method: 'post',
contentType: contentType.formData,
status: {
401: '用户名或者密码错误'
}
}
]
}
3. request.js 方法
// request.js
import axios from 'axios'
import qs from 'qs'
import contentType from '@/config/content-type'
import apiConf from '@/config/api-sdk-conf'
var api = {}
// render 函数用来渲染路径上的变量, 算是一个微型的模板渲染工具
// 例如render('/{{userId}}/{{type}}/{{query}}', {userId:1,type:2, query:3})
// 会被渲染成 /1/2/3
function render (tpl, data) {
var re = /{{([^}]+)?}}/
var match = ''
while ((match = re.exec(tpl))) {
tpl = tpl.replace(match[0], data[match[1]])
}
return tpl
}
// fire中的this, 会动态绑定到每个接口上
function fire (query = {}, payload = '') {
// qs 特别处理 formData类型的数据
if (this.contentType === contentType.formData) {
payload = qs.stringify(payload)
}
// 直接返回axios实例,方便调用then,或者catch方法
return axios({
method: this.method,
url: render(this.url, query),
data: payload,
headers: {
contentType: this.contentType
}
})
}
apiConf.apis.forEach((item) => {
api[item.name] = {
url: apiConf.baseURL + item.path,
method: item.method,
status: item.status,
contentType: item.contentType,
fire: fire
}
})
export default api
4. 在组件中使用
import api from '@/apis/request'
...
api.login.fire({id: '?heiheihei'}, {
username: 'admin',
password: 'admin',
namespace: '_system'
})
...
内容版权声明:除非注明,否则皆为本站原创文章。
