vue---axios

Vue 本來有一個官方推薦的 ajax 插件 vue-resource,可是自從 Vue 更新到 2.0 以後,官方就再也不更新 vue-resource。vue

目前主流的 Vue 項目,都選擇 axios 來完成 ajax 請求,而大型項目都會使用 Vuex 來管理數據,因此這篇博客將結合二者來發送請求ios

npm安裝: git

npm install axios --save

(一)、只使用axios配置github

注:安裝其餘插件的時候,能夠直接在 main.js 中引入並使用 Vue.use()來註冊,可是 axios並非vue插件,因此不能 使用Vue.use(),因此只能在每一個須要發送請求的組件中即時引入。ajax

爲了解決這個問題,有兩種開發思路,一是在引入 axios 以後,修改原型鏈,二是結合 Vuex,封裝一個 aciton。npm

下面介紹的是經過修改原型來配置:axios

import axios from 'axios' 
Vue.prototype.$http = axios

($http這個名字是隨便起的,但要帶上$,而且要與請求方式前面的名字保持一致!!!)api

main.js(全局配置)函數

import axios from 'axios' 
Vue.prototype.$http = axios

get請求:vue-resource

this.$http.get('/user?ID=12345')// 向具備指定ID的用戶發出請求 
.then(function (response) { console.log(response); }) 
.catch(function (error) { console.log(error); });

或

this.$http.get('/user', {//也能夠經過 params 對象傳遞參數 params: { ID: 12345 } }) 
.then(function (response) { console.log(response); }) 
.catch(function (error) { console.log(error); });

(二)、使用axios和vue-axios結合配置(不須要原型配置)

import Vue from 'vue'

import axios from 'axios'

import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

get請求:

this.axios.get('/user?ID=12345') 
.then(function (response) { console.log(response); }) 
.catch(function (error) { console.log(error); });

或

this.axios.get('/user', { params: { ID: 12345 } }) 
.then(function (response) { console.log(response); }) 
.catch(function (error) { console.log(error); });

 

附錄:配置 axios 

上面封裝的方法中,使用了 axios 的三個配置項,實際上只有 url 是必須的,完整的 api 能夠參考使用說明

爲了方便,axios 還爲每種方法起了別名,好比上面的 saveForm 方法等價於:

axios.post('/user', context.state.test02)

完整的請求還應當包括 .then 和 .catch

.then(function(res){ console.log(res) }) 
.catch(function(err){ console.log(err) })

當請求成功時,會執行 .then,不然執行 .catch

這兩個回調函數都有各自獨立的做用域,若是直接在裏面訪問 this,沒法訪問到 Vue 實例

這時只要添加一個 .bind(this) 就能解決這個問題

.then(function(res){ console.log(this.data) }.bind(this))
本站公眾號
   歡迎關注本站公眾號,獲取更多信息