Home > Enterprise >  How to create axios plugin in Vue 3 composition api
How to create axios plugin in Vue 3 composition api

Time:08-05

I am using Vue 3 composition api and typescript .

I want to make Axios plugin to use in my project .

this is my code

plugins/axios.js

import axios from 'axios'
const axiosInstance = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
})
export default {
    install: (app, options) => {
        app.config.globalProperties.$axios={ ...axiosInstance }
    }
}

main.ts

import { createApp } from 'vue'

import axiosPlugin from '@/plugins/axios.js'


import App from './App.vue'

const app = createApp(App)

app.use(axiosPlugin, {})

app.mount('#app')

my component

<script setup lang="ts">
import { $axios } from 'vue'

But I have error in last code section

Module '"vue"' has no exported member '$axios'.ts(2305)

enter image description here

maybe something is wrong in declaring plugin for axios

what's the problem ?

CodePudding user response:

Your axios plugin is not exposed in the Vue library, so importing is not going to work. Your plugin is hooked to the Vue instance. In Vue 2 (or options API) you could use this keyword but in the setup method you need to use getCurrentInstance. Try this

<script setup lang='ts'>
    import { getCurrentInstance } from 'vue'

    const app = getCurrentInstance()
    const axios = app.appContext.config.globalProperties.$axios
</script>

Alternatively you can use provide/inject methods.
In your main.ts

app.provide('axios', axiosInstance);

In your component

import { inject } from 'vue';
const axios = inject('axios');
  • Related