Vuejs如何通過Axios請求數(shù)據(jù)
通過Axios請求數(shù)據(jù)
我們來搭建api接口調(diào)用工具Axios。Vue本身是不支持ajax調(diào)用的,如果你需要這些功能就需要安裝對應(yīng)的工具。
支持ajax請求的工具很多,像superagent和axios。今天我們用的就是axios,因為聽說最近網(wǎng)上大部分的教程書籍都使用的是axios,本身axios這個工具就已經(jīng)做了很好的優(yōu)化和封裝,但是在使用時,還是比較繁瑣,所以我們來重新封裝一下。
安裝Axios工具
cnpm install axios -D
在安裝的時候,一定要切換進(jìn)入咱們的項目根目錄,再運(yùn)行安裝命令,然后如提示以上信息,則表示安裝完成。
封裝Axios工具
編輯src/api/index.js文件(我們在上一章整理目錄結(jié)構(gòu)時,在src/api/目錄新建了一個空的index.js文件),現(xiàn)在我們?yōu)樵撐募顚憙?nèi)容。
// 配置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() } // 參數(shù)過濾函數(shù) 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 } /* 接口處理函數(shù) 這個函數(shù)每個項目都是不一樣的,我現(xiàn)在調(diào)整的是適用于 https://cnodejs.org/api/v1 的接口,如果是其他接口 需要根據(jù)接口的參數(shù)進(jìn)行調(diào)整。參考說明文檔地址: https://cnodejs.org/topic/5378720ed6e2d16149fa16bd 主要是,不同的接口的成功標(biāo)識和失敗提示是不一致的。 另外,不同的項目的處理方法也是不一致的,這里出錯就是簡單的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模板中的調(diào)用接口 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) } }
更多關(guān)于AxIos的解釋請參見:https://github.com/mzabriskie/axios
配置Axios工具
我們在使用之前,需要在src/main.js中進(jìn)行簡單的配置,先來看一下原始的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 文件,將代碼調(diào)整為以下代碼:
<template> ? ? <div>index page</div> </template> <script> export default { ? ? created () { ? ? ? ? this.$api.get('topics', null, r => { ? ? ? ? ? ? console.log(r) ? ? ? ? }) ? ? } } </script>
我們在Index.vue中向瀏覽器的控制臺輸入一些接口請求到的數(shù)據(jù),如果你和我也一樣,那說明我們的接口配置完成正確。如下圖:
如果你是按我的操作一步一步來,那最終結(jié)果應(yīng)該和我一樣。如果出錯請仔細(xì)檢查代碼
Vue請求數(shù)據(jù)(Axios)
什么是Axios
Axios 是一個基于 Promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
Vue.js 2.0 版本推薦使用 axios 來完成 ajax 請求。
引入
引入時不必糾結(jié)與vue的先后順序,它并不依賴與vue
使用方法
1.get請求
get中就只有一個參數(shù),這個參數(shù)中包括前面的地址,后面?zhèn)鞯膮?shù)用“?”拼接在地址后
? ? ? ? created() { ? ? ? ? ? axios ? ? ? ? ? ? .get( ? ? ? ? ? ? ? "http://wkt.myhope365.com/weChat/applet/course/banner/list?number=4" ? ? ? ? ? ? ) ? ? ? ? ? ? .then((res) => { ? ? ? ? ? ? ? ? console.log(res); ? ? ? ? ? ? ? this.imgList = res.data.data; ? ? ? ? ? ? }); ? ? ? ? },
2.post請求(form格式)
要先定義一個form把想要傳的參數(shù)放進(jìn)去
有兩個參數(shù):請求地址,form
? ? ? ? ?created() { ? ? ? ? ? ? let from = new FormData(); ? ? ? ? ? from.append("type", "boutique"); ? ? ? ? ? from.append("pageNum", 2); ? ? ? ? ? from.append("pageSize", 10); ? ? ? ? ? axios ? ? ? ? ? ? .post("http://wkt.myhope365.com/weChat/applet/course/list/type", from) ? ? ? ? ? ? .then((res) => { ? ? ? ? ? ? ? console.log(res); ? ? ? ? ? ? ? this.courseList = res.data.rows; ? ? ? ? ? ? // ? console.log(this.courseList); ? ? ? ? ? ? }); ? ? ? ? },
3.post請求(JOSN格式)
這種情況下,有兩個參數(shù):請求地址,{傳的參數(shù)}
但傳的參數(shù)要以JOSN的格式
created() {? ? ? ? ?? ? ? ? ? ? axios ? ? ? ? ? ? .post("http://wkt.myhope365.com/weChat/applet/subject/list", { ? ? ? ? ? ? ? enable: 1, ? ? ? ? ? ? }) ? ? ? ? ? ? .then((res) => { ? ? ? ? ? ? ? console.log(res); ? ? ? ? ? ? ? this.list = res.data.rows; ? ? ? ? ? ? ? console.log(this.list); ? ? ? ? ? ? }); ? ? ? ? },
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue雙擊事件2.0事件監(jiān)聽(點(diǎn)擊-雙擊-鼠標(biāo)事件)和事件修飾符操作
這篇文章主要介紹了vue雙擊事件2.0事件監(jiān)聽(點(diǎn)擊-雙擊-鼠標(biāo)事件)和事件修飾符操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07解決vue項目打包上服務(wù)器顯示404錯誤,本地沒出錯的問題
這篇文章主要介紹了解決vue項目打包上服務(wù)器顯示404錯誤,本地沒出錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11webpack項目調(diào)試以及獨(dú)立打包配置文件的方法
下面小編就為大家分享一篇webpack項目調(diào)試以及獨(dú)立打包配置文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02vant-list組件觸發(fā)多次onload事件導(dǎo)致數(shù)據(jù)亂序的解決方案
這篇文章主要介紹了vant-list組件觸發(fā)多次onload事件導(dǎo)致數(shù)據(jù)亂序的解決方案2023-01-01解決vue中axios設(shè)置超時(超過5分鐘)沒反應(yīng)的問題
這篇文章主要介紹了解決vue中axios設(shè)置超時(超過5分鐘)沒反應(yīng)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09Vue.js做select下拉列表的實例(ul-li標(biāo)簽仿select標(biāo)簽)
下面小編就為大家分享一篇Vue.js做select下拉列表的實例(ul-li標(biāo)簽仿select標(biāo)簽),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03