Import Axios Method Globally in Vuejs
You can create a plugin and use it like this in your main.js
file (if you're using something like vue-cli)
import axios from 'axios'Vue.use({ install (Vue) { Vue.prototype.$api = axios.create({ baseURL: 'http://localhost:8000/api/' }) }})new Vue({ // your app here})
Now, you can do this.$api.get(...)
on every component method
Read more about Vue plugins here: https://vuejs.org/v2/guide/plugins.html
Provide/Inject could be an option as well: https://vuejs.org/v2/api/#provide-inject
There is a window object available to you in the browser. You can actively leverage that based on your requirements.
In the main.js file
import axiosApi from 'axios';const axios = axiosApi.create({ baseURL:`your_base_url`, headers:{ header:value }});//Use the window object to make it available globally.window.axios = axios;
Now in your component.vue
methods:{ someMethod(){ axios.get('/endpoint').then(res => {}).catch(err => {}); }}
This is basically how I use axios globally in my projects. Also, this is also how Laravel uses it.
Keeping this in main.js
works perfectly fine for me in Vue 3.
import { createApp } from 'vue';import App from './App.vue';import axios from "axios";const app = createApp(App);const instance = axios.create({ baseURL: 'https://example.com/', });app.config.globalProperties.axios=instanceapp.mount('#app');
and to use it in any component,
this.axios.post('/helloworld', { name: this.name, age: this.age})