Loading

【Vue】在 Vue 中使用 axios

把 axios 挂载到 Vue 的原型上

  1. main.js 中导入 axios,并挂载到 Vue 的 prototype 上:

    import Vue from 'vue'
    import App from './App.vue'
    import axios from 'axios'
    
    Vue.prototype.axios = axios
    
    new Vue({
      render: (h) => h(App)
    }).$mount('#app')
    
  2. 这样在每个组件中使用 axios 发请求时就不需要每次都导入了,直接使用 this.axios 就能得到 axios

    <script>
    export default {
      methods: {
        getInfo() {
          this.axios.get('./cartData.json').then((res) => {
            console.log(res.data)
          })
        }
      }
    }
    </script>
    

配置请求根路径

main.js 中进行配置:

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'

Vue.config.productionTip = false

// 配置 axios 的请求根路径
axios.defaults.baseURL = 'http://httpbin.org:80'
Vue.prototype.axios = axios

new Vue({
  render: (h) => h(App)
}).$mount('#app')

配置了请求根路径之后,以后用 axios 发请求就不需要写全路径了。

  • 配置前:

    this.axios.get('http://httpbin.org:80/get').then((res) => {
        console.log(res.data)
    })
    
  • 配置后:

    this.axios.get('/get').then((res) => {
        console.log(res.data)
    })
    
posted @ 2022-05-31 20:18  Skyey  阅读(644)  评论(0编辑  收藏  举报