Vue全局使用axios-1

Vue全局使用axios

main.js

  • 在main.js中引入以后就可以在所有組件中通過 this.$axios({...}) 使用
import axios from 'axios'

Vue.prototype.$axios = axios
  • 全局配置axios
    • 可以配置的東西很多我這里配置了全局的baseURL這樣不用每一個都寫一遍http://localhost:3000
Vue.prototype.$axios = Axios.create({
  baseURL: 'http://localhost:3000'
})

其他組件中使用

this.$axios({
        method: 'post',
        url:  path,
        data: data
      }).then(response => {
        console.log(response.data)
        console.log(response.status)
        console.log(response.statusText)
        console.log(response.headers)
        console.log(response.config)
      })

Axios 多請求處理

// 請求結果按請求順序返回一個數(shù)組
this.$axios.all([
  this.$axios.get(`http://localhost:3000`),
  this.$axios.get(`http://localhost:3000`),
  this.$axios.get(`http://localhost:3000`),
  this.$axios.get(`http://localhost:3000`)
]).then(response => {
  response.forEach((value, key) => {
    console.log(value)
  })
}
// 返回結果可以使用axios.spread()解析處理
this.$axios.all([
  this.$axios.get(`http://localhost:3000`),
  this.$axios.get(`http://localhost:3000`),
  this.$axios.get(`http://localhost:3000`),
  this.$axios.get(`http://localhost:3000`)
]).then(this.$axios.spread((data1, data2, data3, data4) => {

})

具體axios使用可以參考

http://www.itdecent.cn/p/6c4bfe3dd0d8

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 這個主題我一直想寫,在內(nèi)心的深處一直覺得自己對家人有愧疚之感,尤其是自己的愛人!我現(xiàn)在能有這樣的生活,離不開...
    金虎啟程007閱讀 875評論 1 2
  • 那個時候,他已經(jīng)在大學了。 那是一所歷史悠久的大學,占地面積極大。學校的后身,有一座山丘,當時建校,也許是為了方便...
    微光斜雨閱讀 210評論 1 1

友情鏈接更多精彩內(nèi)容