這次給大家帶來vue中ajax請求與axios包完美處理,vue中ajax請求與axios包處理的注意事項有哪些,下面就是實戰案例,一起來看一下。
在vue中,經常會用到數據請求,常用的有:vue-resourse、axios
今天我說的是axios的post請求
github源文件及文檔地址:【https://github.com/axios/axios】
+ 首先,引入axiosCDN:
npm: npm install axios 并在全局的js中引入:import axios from 'axios';
?get請求axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
?post請求依賴于qs包,將對象轉換成以&連接的字符串
//例:
axios.post( postUrl ,qs.stringify({userid:1,username:'yyy'})).then(function (response) {
console.log(response);
})
附錄:配置 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))
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀: