2

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 ?

1 Answer 1

4

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');
Sign up to request clarification or add additional context in comments.

3 Comments

i think you meant add app.provide('axios', axiosInstance); in plugin am I right ?
yeah, depends on how you see it, check out this link: skirtles-code.github.io/vue-examples/patterns/…
Bur i have type script error in component for axios.get('/') it said "Object is of type 'unknown'.ts(2571)" can you help with that ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.