vue2.0的ajax


Vue 原本有一個官方推薦的 ajax 插件 vue-resource,但是自從 Vue 更新到 2.0 之后,官方就不再更新 vue-resource

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

Vuex 的安裝將不再贅述,可以參考之前的Vue.js實戰之Vuex的入門教程

使用 cnpm 安裝 axios

?
1
cnpm install axios -S

安裝其他插件的時候,可以直接在 main.js 中引入並 Vue.use(),但是 axios 並不能 use,只能每個需要發送請求的組件中即時引入

為了解決這個問題,有兩種開發思路,一是在引入 axios 之后,修改原型鏈,二是結合 Vuex,封裝一個 aciton。具體的實施請往下看~

方案一:改寫原型鏈

首先在 main.js 中引入 axios

?
1
import axios from 'axios'

這時候如果在其它的組件中,是無法使用 axios 命令的。但如果將 axios 改寫為 Vue 的原型屬性,就能解決這個問題

?
1
Vue.prototype.$ajax = axios

在 main.js 中添加了這兩行代碼之后,就能直接在組件的 methods 中使用 $ajax 命令

?
1
2
3
4
5
6
7
8
9
10
11
methods: {
  submitForm () {
  this .$ajax({
   method: 'post' ,
   url: '/user' ,
   data: {
   name: 'wise' ,
   info: 'wrong'
   }
  })
}

方案二:在 Vuex 中封裝

之前的文章中用到過 Vuex 的 mutations,從結果上看,mutations 類似於事件,用於提交 Vuex 中的狀態 state

action 和 mutations 也很類似,主要的區別在於,action 可以包含異步操作,而且可以通過 action 來提交 mutations

另外還有一個重要的區別:

mutations 有一個固有參數 state,接收的是 Vuex 中的 state 對象

action 也有一個固有參數 context,但是 context 是 state 的父級,包含  state、getters

Vuex 的倉庫是 store.js,將 axios 引入,並在 action 添加新的方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// store.js
import Vue from 'Vue'
import Vuex from 'vuex'
 
// 引入 axios
import axios from 'axios'
 
Vue.use(Vuex)
 
const store = new Vuex.Store({
  // 定義狀態
  state: {
  test01: {
   name: 'Wise Wrong'
  },
  test02: {
   tell: '12312345678'
  }
  },
  actions: {
  // 封裝一個 ajax 方法
  saveForm (context) {
   axios({
   method: 'post' ,
   url: '/user' ,
   data: context.state.test02
   })
  }
  }
})
 
export default store

注意:即使已經在 main.js 中引入了 axios,並改寫了原型鏈,也無法在 store.js 中直接使用 $ajax 命令

換言之,這兩種方案是相互獨立的

在組件中發送請求的時候,需要使用 this.$store.dispatch 來分發

?
1
2
3
4
5
methods: {
  submitForm () {
  this .$store.dispatch( 'saveForm' )
  }
}

submitForm 是綁定在組件上的一個方法,將觸發 saveForm,從而通過 axios 向服務器發送請求

附:配置 axios

上面封裝的方法中,使用了 axios 的三個配置項,實際上只有 url 是必須的。

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

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

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

?
1
2
3
4
5
6
.then(function(res){
  console.log(res)
})
.catch(function(err){
  console.log(err)
})

當請求成功時,會執行 .then,否則執行 .catch

總結

原文鏈接:http://www.cnblogs.com/wisewrong/p/6402183.html


免責聲明!

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



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