axios vue 回调函数_vue中ajax请求与axios包完美处理
這次給大家?guī)韛ue中ajax請求與axios包完美處理,vue中ajax請求與axios包處理的注意事項有哪些,下面就是實戰(zhàn)案例,一起來看一下。
在vue中,經(jīng)常會用到數(shù)據(jù)請求,常用的有: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)
})
當請求成功時,會執(zhí)行 .then,否則執(zhí)行 .catch
這兩個回調函數(shù)都有各自獨立的作用域,如果直接在里面訪問 this,無法訪問到 Vue 實例
這時只要添加一個 .bind(this) 就能解決這個問題.then(function(res){
console.log(this.data)
}.bind(this))
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關注php中文網(wǎng)其它相關文章!
推薦閱讀:
總結
以上是生活随笔為你收集整理的axios vue 回调函数_vue中ajax请求与axios包完美处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021年值得推荐的几个可视化软件
- 下一篇: 软件测试简历常见问题