前言
在vue中,請求后端接口的模塊有三種:
- vue-resource
- axios
- fetch
這我們使用axios去請求后端接口。
安裝
進入vue項目的目錄,執行:
npm install axios --save
使用
axios支持的http請求方法如下
- axios.request(config)
- axios.get(url[, config])
- axios.delete(url[, config])
- axios.head(url[, config])
- axios.options(url[, config])
- axios.post(url[, data[, config]])
- axios.put(url[, data[, config]])
- axios.patch(url[, data[, config]])
本篇不重點介紹axios的使用,這里我們以get為例,在使用axios接收接口返回的時候,需要使用箭頭=>符號獲取正確的this指針。
this.$axios .get("/userInfo") .then( (response) => // handle success (this.userdata = response.data) ) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed });
如果不想用箭頭函數可以在外部先用變量獲取this指針,但是建議還是使用上面的寫法。
let that = this;
this.$axios .get("/userInfo") .then( function(response){
// handle success (that.userdata = response.data) ) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed });
博主:測試生財(一個不為996而996的測開碼農)
座右銘:專注測試開發與自動化運維,努力讀書思考寫作,為內卷的人生奠定財務自由。
內容范疇:技術提升,職場雜談,事業發展,閱讀寫作,投資理財,健康人生。
csdn:https://blog.csdn.net/ccgshigao
博客園:https://www.cnblogs.com/qa-freeroad/
51cto:https://blog.51cto.com/14900374
微信公眾號:測試生財(定期分享獨家內容和資源)