vue2.0 axios前後端資料處理
阿新 • • 發佈:2019-01-09
目前主流的 Vue 專案,都選擇 axios 來完成 ajax 請求,而大型專案都會使用 Vuex 來管理資料。
前言:
使用 cnpm 安裝 axios
cnpm install axios -S
安裝其他外掛的時候,可以直接在 main.js 中引入並 Vue.use(),但是 axios 並不能 use,只能每個需要傳送請求的元件中即時引入
為了解決這個問題,是在引入 axios 之後,修改原型鏈具體的實施請往下看~
改寫原型鏈
首先在 main.js 中引入 axios
import axios from 'axios'
這時候如果在其它的元件中,是無法使用 axios 命令的。但如果將 axios 改寫為 Vue 的原型屬性,就能解決這個問題
Vue.prototype.$ajax = axios
在 main.js 中添加了這兩行程式碼之後,就能直接在元件的 methods 中使用 $ajax 命令
methods: {
but_ajax() {
this.$ajax({
method: 'post',
url: 'http://192.168.0.113:8080/llhb/m/requirement/allCategor',
params: { //需要傳送的資料
name: 'zhangwenwu2',
age: '15'
}
})
//請求成功後執行then 如果直接在裡面訪問 this,無法訪問到 Vue 例項,this指向發生了變化。建議使用箭頭函式,下面有講
.then(function (response) {
console.log(response); //處理後臺返回的資料
})
//請求失敗後執行catch
.catch(function(err){
console.log(err)
})
}
附錄:配置 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 例項,this指向發生了變化。
這時只要新增一個 .bind(this) 就能解決這個問題,或者使用箭頭函式即可
.then(function(res){
console.log(this.data)
}.bind(this))
.then((res) => {
console.log(this.data)
})