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 多请求处理

// 请求结果按请求顺序返回一个数组
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.jianshu.com/p/6c4bfe3dd0d8

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 这个主题我一直想写,在内心的深处一直觉得自己对家人有愧疚之感,尤其是自己的爱人!我现在能有这样的生活,离不开...
    金虎启程007阅读 4,181评论 1 2
  • 那个时候,他已经在大学了。 那是一所历史悠久的大学,占地面积极大。学校的后身,有一座山丘,当时建校,也许是为了方便...
    微光斜雨阅读 1,423评论 1 1

友情链接更多精彩内容