上一章,我们认识了项目的目录结构,以及对项目的目录结构做了一些调整,已经能把项目重新跑起来了。今天我们来搭建api接口调用工具Axios。Vue本身是不支持ajax调用的,如果你需要这些功能就需要安装对应的工具。
支持ajax请求的工具很多,像superagent和axios。今天我们用的就是axios,因为听说最近网上大部分的教程书籍都使用的是axios,本身axios这个工具就已经做了很好的优化和封装,但是在使用时,还是比较繁琐,所以我们来重新封装一下。
安装Axios工具
1cnpm install axios -D
在安装的时候,一定要切换进入咱们的项目根目录,再运行安装命令,然后如提示以上信息,则表示安装完成。
封装Axios工具
编辑src/api/index.js文件(我们在上一章整理目录结构时,在src/api/目录新建了一个空的index.js文件),现在我们为该文件填写内容。
1// 配置API接口地址
2var root = 'https://cnodejs.org/api/v1'
3// 引用axios
4var axios = require('axios')
5// 自定义判断元素类型JS
6function toType (obj) {
7 return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
8}
9// 参数过滤函数
10function filterNull (o) {
11 for (var key in o) {
12 if (o[key] === null) {
13 delete o[key]
14 }
15 if (toType(o[key]) === 'string') {
16 o[key] = o[key].trim()
17 } else if (toType(o[key]) === 'object') {
18 o[key] = filterNull(o[key])
19 } else if (toType(o[key]) === 'array') {
20 o[key] = filterNull(o[key])
21 }
22 }
23 return o
24}
25
26/*
27 接口处理函数
28 这个函数每个项目都是不一样的,我现在调整的是适用于
29 https://cnodejs.org/api/v1 的接口,如果是其他接口
30 需要根据接口的参数进行调整。参考说明文档地址:
31 https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
32 主要是,不同的接口的成功标识和失败提示是不一致的。
33 另外,不同的项目的处理方法也是不一致的,这里出错就是简单的alert
34*/
35function apiAxios (method, url, params, success, failure) {
36 if (params) {
37 params = filterNull(params)
38 }
39 axios({
40 method: method,
41 url: url,
42 data: method === 'POST' || method === 'PUT' ? params : null,
43 params: method === 'GET' || method === 'DELETE' ? params : null,
44 baseURL: root,
45 withCredentials: false
46 })
47 .then(function (res) {
48 if (res.data.success === true) {
49 if (success) {
50 success(res.data)
51 }
52 } else {
53 if (failure) {
54 failure(res.data)
55 } else {
56 window.alert('error: ' + JSON.stringify(res.data))
57 }
58 }
59 })
60 .catch(function (err) {
61 let res = err.response
62 if (err) {
63 window.alert('api error, HTTP CODE: ' + res.status)
64 }
65 })
66}
67// 返回在vue模板中的调用接口
68export default {
69 get: function (url, params, success, failure) {
70 return apiAxios('GET', url, params, success, failure)
71 },
72 post: function (url, params, success, failure) {
73 return apiAxios('POST', url, params, success, failure)
74 },
75 put: function (url, params, success, failure) {
76 return apiAxios('PUT', url, params, success, failure)
77 },
78 delete: function (url, params, success, failure) {
79 return apiAxios('DELETE', url, params, success, failure)
80 }
81}
更多关于AxIos的解释请参见:https://github.com/mzabriskie/axios
配置Axios工具
我们在使用之前,需要在src/main.js中进行简单的配置,先来看一下原始的main.js文件
1// The Vue build version to load with the `import` command
2// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
3import Vue from 'vue'
4import App from './App'
5import router from './router'
6
7Vue.config.productionTip = false
8
9/* eslint-disable no-new */
10 new Vue({
11 el: '#app',
12 router,
13 template: '<App/>',
14 components: { App }
15})
修改为:
1// The Vue build version to load with the `import` command
2// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
3import Vue from 'vue'
4import App from './App'
5import router from './router'
6
7// 引用API文件
8import api from './api/index.js'
9// 将API方法绑定到全局
10Vue.prototype.$api = api
11
12Vue.config.productionTip = false
13
14/* eslint-disable no-new */
15new Vue({
16 el: '#app',
17 router,
18 template: '<App/>',
19 components: { App }
20})
通过以上的配置,我们就可以在项目中使用axios工具了,接下来我们来测试一下这个工具。
使用Axios工具
我们来修改一下 src/page/Index.vue 文件,将代码调整为以下代码:
1<template>
2 <div>index page</div>
3</template>
4<script>
5export default {
6 created () {
7 this.$api.get('topics', null, r => {
8 console.log(r)
9 })
10 }
11}
12</script>
我们在Index.vue中向浏览器的控制台输入一些接口请求到的数据,如果你和我也一样,那说明我们的接口配置完成正确。如下图:
如果你是按我的操作一步一步来,那最终结果应该和我一样。如果出错请仔细检查代码。