首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

Vue全局使用axios-1

2024-12-15 来源:化拓教育网

Vue全局使用axios

main.js

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

Vue.prototype.$axios = axios
  • 全局配置axios
    • 可以配置的东西很多我这里配置了全局的baseURL这样不用每一个都写一遍
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使用可以参考

显示全文