4、VueJs 填坑日记之搭建Axios接口请求工具

上一章,咱们认识了项目的目录结构,以及对项目的目录结构作了一些调整,已经能把项目从新跑起来了。今天咱们来搭建api接口调用工具Axios。Vue自己是不支持ajax调用的,若是你须要这些功能就须要安装对应的工具。javascript

支持ajax请求的工具不少,像superagent和axios。今天咱们用的就是axios,由于据说最近网上大部分的教程书籍都使用的是axios,自己axios这个工具就已经作了很好的优化和封装,可是在使用时,仍是比较繁琐,因此咱们来从新封装一下。vue

安装Axios工具java

cnpm install axios -D

 

在安装的时候,必定要切换进入我们的项目根目录,再运行安装命令,而后如提示以上信息,则表示安装完成。node

 

封装Axios工具
编辑src/api/index.js文件(咱们在上一章整理目录结构时,在src/api/目录新建了一个空的index.js文件),如今咱们为该文件填写内容。webpack

// 配置API接口地址
var root = 'https://cnodejs.org/api/v1'
// 引用axios
var axios = require('axios')
// 自定义判断元素类型JS
function toType (obj) {
	return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull (o) {
	for (var key in o) {
		if (o[key] === null) {
			delete o[key]
		}
		if (toType(o[key]) === 'string') {
			o[key] = o[key].trim()
		} else if (toType(o[key]) === 'object') {
			o[key] = filterNull(o[key])
		} else if (toType(o[key]) === 'array') {
			o[key] = filterNull(o[key])
		}
	}
	return o
}

/*
  接口处理函数
  这个函数每一个项目都是不同的,我如今调整的是适用于
  https://cnodejs.org/api/v1 的接口,若是是其余接口
  须要根据接口的参数进行调整。参考说明文档地址:
  https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
  主要是,不一样的接口的成功标识和失败提示是不一致的。
  另外,不一样的项目的处理方法也是不一致的,这里出错就是简单的alert
*/
function apiAxios (method, url, params, success, failure) {
	if (params) {
		params = filterNull(params)
	}
	axios({
		method: method,
		url: url,
		data: method === 'POST' || method === 'PUT' ? params : null,
		params: method === 'GET' || method === 'DELETE' ? params : null,
		baseURL: root,
		withCredentials: false
	})
	.then(function (res) {
	if (res.data.success === true) {
		if (success) {
			success(res.data)
		}
	} else {
		if (failure) {
			failure(res.data)
		} else {
			window.alert('error: ' + JSON.stringify(res.data))
		}
	}
	})
	.catch(function (err) {
		let res = err.response
		if (err) {
			window.alert('api error, HTTP CODE: ' + res.status)
		}
	})
}

// 返回在vue模板中的调用接口
export default {
	get: function (url, params, success, failure) {
		return apiAxios('GET', url, params, success, failure)
	},
	post: function (url, params, success, failure) {
		return apiAxios('POST', url, params, success, failure)
	},
	put: function (url, params, success, failure) {
		return apiAxios('PUT', url, params, success, failure)
	},
	delete: function (url, params, success, failure) {
		return apiAxios('DELETE', url, params, success, failure)
	}
}

更多关于AxIos的解释请参见:https://github.com/mzabriskie/axiosios

配置Axios工具
咱们在使用以前,须要在src/main.js中进行简单的配置,先来看一下原始的main.js文件git

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
    new Vue({
    el: '#app',
    router,
    template: '<App/>',
    components: { App }
})

修改成:github

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

// 引用API文件
import api from './api/index.js'
// 将API方法绑定到全局
Vue.prototype.$api = api

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    template: '<App/>',
    components: { App }
})

经过以上的配置,咱们就能够在项目中使用axios工具了,接下来咱们来测试一下这个工具。web

使用Axios工具
咱们来修改一下 src/page/Index.vue 文件,将代码调整为如下代码:ajax

<template>
    <div>index page</div>
</template>
<script>
export default {
    created () {
        this.$api.get('topics', null, r => {
            console.log(r)
        })
    }
}
</script>

咱们在Index.vue中向浏览器的控制台输入一些接口请求到的数据,若是你和我也同样,那说明咱们的接口配置完成正确。以下图:

若是你是按个人操做一步一步来,那最终结果应该和我同样。若是出错请仔细检查代码。

相关文章
相关标签/搜索