在vue中,經常會用到數據請求,常用的有:vue-resourse、axios
今天我說的是axios的post請求
github源文件及文檔地址:【https://github.com/axios/axios】
+ 首先,引入axios
CDN: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>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))
總結
以上所述是小編給大家介紹的關于vue中的ajax請求和axios包問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答