前言
在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
微信公衆号:測試生财(定期分享獨家内容和資源)
![]()
vue踩坑:axios使用this指針