四、VueJs 填坑日記之搭建Axios接口請求工具


上一章,我們認識了項目的目錄結構,以及對項目的目錄結構做了一些調整,已經能把項目重新跑起來了。今天我們來搭建api接口調用工具Axios。Vue本身是不支持ajax調用的,如果你需要這些功能就需要安裝對應的工具。

支持ajax請求的工具很多,像superagent和axios。今天我們用的就是axios,因為聽說最近網上大部分的教程書籍都使用的是axios,本身axios這個工具就已經做了很好的優化和封裝,但是在使用時,還是比較繁瑣,所以我們來重新封裝一下。

安裝Axios工具

cnpm install axios -D

 

在安裝的時候,一定要切換進入咱們的項目根目錄,再運行安裝命令,然后如提示以上信息,則表示安裝完成。

 

封裝Axios工具
編輯src/api/index.js文件(我們在上一章整理目錄結構時,在src/api/目錄新建了一個空的index.js文件),現在我們為該文件填寫內容。

// 配置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/axios

配置Axios工具
我們在使用之前,需要在src/main.js中進行簡單的配置,先來看一下原始的main.js文件

// 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 }
})

修改為:

// 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工具了,接下來我們來測試一下這個工具。

使用Axios工具
我們來修改一下 src/page/Index.vue 文件,將代碼調整為以下代碼:

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

我們在Index.vue中向瀏覽器的控制台輸入一些接口請求到的數據,如果你和我也一樣,那說明我們的接口配置完成正確。如下圖:

如果你是按我的操作一步一步來,那最終結果應該和我一樣。如果出錯請仔細檢查代碼。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM