vue3之axios配置(阿飞)

本文介绍了在Vue3中如何配置和使用Axios进行HTTP请求,包括在main.js中全局引入Axios,设置默认基础URL,并通过全局属性和mixin方法使各个组件能访问Axios。同时,也讲解了Vue3的新特性——组合式API,在没有`this`的情况下如何通过`getCurrentInstance`获取组件实例并使用HTTP请求。最后,还展示了如何利用provide和inject进行依赖注入,使得子组件可以访问到Axios实例。

1.使用npm i axios --save

2.全局使用 main.js中

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { showMixin } from './mixins/index'
// import axios from 'vue-axios'
import axios from 'axios'
// import VueCompositionApi from '@vue/composition-api'
// createApp(App).config.productionTip = false
// createApp(App).use(store).use(router).use(VueCompositionApi).mount('#app')
// =========配置minxin
// createApp(App).mixin(showMixin).use(store).use(router).mount('#app')
// ===========配置axios
const app = createApp(App)
axios.defaults.baseURL = 'http://www.kymid.com/testphp/public/index.php/api/'
app.config.globalProperties.$http = axios
app.mixin(showMixin).use(store).use(router).mount('#app')

3.在组件中使用

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <button @click="mymixin">测试mixin</button>
    <button @click="fn">测试mixin</button>
  </div>
</template>
<script>
// import { showMixin } from '../mixins/index'
// export default {
//   mixins: [showMixin]
// }
  export default {
    created () {
      // this.$http.get('http://www.kymid.com/testphp/public/index.php/api/apis/about_get?lang=en').then(val => {
      this.$http.get('apis/about_get?lang=en').then(val => {
        console.log(val)
      })
    }
  }
</script>

方法二:在vue3中,新的组合式[API]没有this,那我们如果需要用到this怎么办?

getCurrentInstance 方法获取当前组件的实例,然后通过 ctxproxy 属性获得当前上下文,这样我们就能在setup中使用router和vuex了

import { getCurrentInstance, onMounted } from 'vue'
 setup (props, context) {
      // 在
      const { proxy } = getCurrentInstance()
      onMounted(() => {
        getData()
      })
      function getData () {
        proxy.$http.get('apis/about_get?lang=en').then(res => {
          console.log(res)
        })
      }
    }

方法三:使用provide 和 inject 方法共享

main.js中:

const app = createApp(App)
axios.defaults.baseURL = 'http://www.kymid.com/testphp/public/index.php/api/'
app.config.globalProperties.$http = axios
// 方法三:
app.provide('$axios', axios)

组件中:

import { getCurrentInstance, onMounted, inject } from 'vue'
// import { inject } from 'vue'
  export default {
    created () {
      // 方式一: 在created中 直接使用this调用
      // this.$http.get('http://www.kymid.com/testphp/public/index.php/api/apis/about_get?lang=en').then(val => {
      this.$http.get('apis/about_get?lang=en').then(val => {
        console.log(val)
      })
    },
    setup (props, context) {
      // 在
      const { proxy } = getCurrentInstance()
      onMounted(() => {
        getData()
      })
      function getData () {
        proxy.$http.get('apis/about_get?lang=en').then(res => {
          console.log(res)
        })
      }
      // 方法三: 使用共享
      const $axios = inject('$axios')
      $axios.get('apis/about_get?lang=en').then((resp) => {
        console.log(resp)
      })
    }
  }

Vue3中,axios是一个常用的HTTP请求库,可以在组件内部方便地发送异步数据请求。为了统一配置全局的axios实例,通常会在Vue的`setup()`函数或main.js文件中设置。以下是配置的基本步骤: 1. 安装axios:首先需要安装axios,可以使用npm或yarn: ```bash npm install axios # 或者 yarn add axios ``` 2. 创建axios实例并配置默认选项:在`setup()`函数或Vue原型上创建一个axios实例,并设置一些全局的配置,例如基础URL、超时时间等。 ```javascript import { createApp } from &#39;vue&#39;; import axios from &#39;axios&#39;; const app = createApp(App); // 在原型上创建axios实例 app.config.globalProperties.$http = axios.create({ baseURL: process.env.BASE_API_URL, // 基础API URL timeout: 5000, // 超时时间(单位:毫秒) headers: { &#39;Content-Type&#39;: &#39;application/json&#39;, Authorization: &#39;Bearer &#39; + localStorage.getItem(&#39;token&#39;) // 如果有认证信息 } }); // 如果需要取消所有请求 app.config.globalProperties.$http.cancelAll = axios.CancelToken.source(); app.mount(&#39;#app&#39;); ``` 3. 使用:现在可以在组件内的任何地方通过`$http`属性来发起请求了,例如获取数据: ```javascript export default { async mounted() { try { const response = await this.$http.get(&#39;/api/users&#39;); console.log(response.data); } catch (error) { if (error instanceof axios.CancelledError) { console.log(&#39;请求已取消&#39;); } else { console.error(error.response.data); } } } }; ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值