15-axios 挂载到全局

141 阅读1分钟

main.js 挂载方式

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

Vue.config.productionTip = false
// axios.defaults.baseURL = '请求根路径'
axios.defaults.baseURL = 'http://www.liulongbin.top:3006'
// 把 axios 挂载到 Vue.prototype 上,供每个 .vue 组件的实例直接使用
Vue.prototype.$http = axios 
// 在每个 .vue 组件中要发起请求,直接调用 this.$hhtp.xxx
new Vue({
  render: h => h(App),
}).$mount('#app')

使用方式

<template>
  <button @click="getinfo">Get 请求</button>
</template>

<script>
export default {
  methods:{
    async getinfo(){
      const {data:res} = await this.$http('/api/get')
      console.log(res)
    }
  }
}
</script>

<style></style>