this is my ~/plugins/axios.js file:
import axios from 'axios'
let api = axios.create({
baseURL: 'http://localhost:8000/api/v1/'
})
export default api
When I want to use axios in every components, I must have write this line:
import api from '~/plugins/axios
How can i config it globally, just write $api instead?
P.A They can be anywhere you want. If you didn't want to clutter main. js just put the statements into a lib/axios. js file or something and add all your interceptors, and then export the axios object, and you can assign it in main.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With