Import Axios Method Globally in Vuejs - vue.js

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?

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://v2.vuejs.org/v2/guide/plugins.html
Provide/Inject could be an option as well: https://v2.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=instance
app.mount('#app');
and to use it in any component,
this.axios.post('/helloworld', {
name: this.name,
age: this.age
})

Related

How to use Axios globally using composition API

I'm having trouble getting Axios to work using the composition API. The following is what I've done, but I'm unsure how to access Axios within setup(). I'm aware that the "this" keyword is no longer available in the composition API.
Created an axio.js file in /plugins:
import axios from 'axios'
export default {
install: (app, options) => {
app.config.globalProperties.axios = axios.create({
baseURL: options.baseUrl,
withCredentials: true,
headers: {
Authorization: options.token ? `Bearer ${options.token}` : '',
}
})
}
}
Added it to plugins/index.js
import { loadFonts } from './webfontloader'
import vuetify from './vuetify'
import pinia from '../store'
import router from '../router'
import axios from './axios'
export function registerPlugins (app) {
loadFonts()
app
.use(vuetify)
.use(pinia)
.use(router)
.use(axios, { baseUrl: import.meta.env.VITE_AXIOS_BASE_URL })
}
Then the main.js file registers all plugins:
import App from './App.vue'
// Composables
import { createApp } from 'vue'
// Plugins
import { registerPlugins } from '#/plugins'
const app = createApp(App)
registerPlugins(app)
app.mount('#app')

Vuex 4 Modules can't use global axios property

I have a Vue3 (without Typescript) app running Vuex 4.0.0.
I'm trying to set up a simple GET request in one of my store modules using axios, however I'm getting a Cannot read property of 'get' of undefined when I try to do it via an action called in one of my components, however if I call this.$axios from the component it works fine. For some reason, my modules can't use this.$axios, while elsewhere in the app I can.
I've declared $axios as a globalProperty in my main.js file.
// main.js
import { createApp } from "vue";
import App from "./App.vue";
import { router } from "./router";
import { store } from "./store";
import axios from "axios";
const app = createApp(App).use(store).use(router);
app.config.globalProperties.$axios = axios;
app.mount("#app");
And the store module looks like this (simplified for the purposes of this question):
// store/modules/example.js
const state = () => ({
message: ""
});
const mutations = {
getMessage(state, payload) {
state.message = payload;
}
};
const actions = {
async setMessage(commit) {
this.$axios.get("example.com/endpoint").then(response => {
commit("setMessage", response.message);
});
}
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
};
The main store/index.js that's getting imported in main.js above looks like this:
// store/index.js
import "es6-promise";
import { createStore } from "vuex";
import example from "./modules/example";
export const store = createStore({ modules: { example } });
In the component, I have the following:
// MyComponent.vue
import { mapGetters, mapActions } from "vuex";
export default {
computed: {
...mapGetters({
message: "example/getMessage"
})
},
methods: {
...mapActions({
getMessage: "example/setMessage"
})
}
};
And a simple button with #click="getMessage". Clicking this button, however, returns Uncaught (in promise) TypeError: Cannot read property 'get' of undefined, but if I copy/paste the setMessage action into a component method, it works just fine.
Is there a way for me to expose this.$axios to the store files?
While this is not the ideal solution, as I would've preferred to have my $axios instance available globally with a single declaration in the mount file, it's probably the next best thing.
I made a lib/axiosConfig.js file that exports an axios instance with some custom axios options, and I just import that one instance in every module that needs it.
import axios from "axios";
axios.defaults.baseURL= import.meta.env.DEV ? "http://localhost:8000": "example.com";
axios.defaults.headers.common["Authorization"] = "Bearer " + localStorage.getItem("token");
axios.defaults.headers.common["Content-Type"] = "application/json";
// etc...
export const $axios = axios.create();
And in whatever module I need $axios in, I just import { $axios } from "./lib/axiosConfig. It's not perfect as I mentioned, since I do still have to import it in every module, but it's close enough as far as I can see, and has the added benefit of using the same axios config everywhere by just importing this file.

How to get access to the Root inside the setup method of Vue 3 component?

I have an Vue App.
I use vuex.
I created my app like this:
import { createApp } from "vue";
import axios from "axios";
import App from "./App.vue";
import router from "./router";
import store from "./store/index";
axios.defaults.baseURL = "https://localhost:44349";
const app = createApp(App)
.use(router)
.use(store)
.mount("#app");
Than i one of my component i am trying to access context.root.$store in the setup() method
, but context.root is undefined.
<script>
import {ref, computed } from "vue";
export default {
name: "ClientList",
setup(props, context) {
const clients = ref([]);
console.log(context);
const clientOrdersLenght = computed(() => {
return clients.value.length;
});
return { clients, clientOrdersLenght }
},
};
</script>
My idea is get acces to my store via context.root. I watched videos and examples with this. but they refer to Vue 2 using 'vue/composition-api' as import.
What i am missing?
You might be able to include and access the store directly
store.dispatch('myModule/myModuleAction')
store.myModule.state.blabla
import {ref, computed } from "vue";
import store from './store/index'; // include store
export default {
name: "ClientList",
setup(props) {
const clients = ref([]);
const clientOrdersLength = computed(() => {
store.dispatch('myAction'); // call dispatch
store.state.myItem // or access store's state
return clients.value.length;
});
return { clients, clientOrdersLength }
},
};
I found an easy way to access my store with getStore() from vuex. That's cool.
But for other reason in the feature, me or somebody else will need to access the $root (vue instance) of the app. So may be now the correct question is how to get the $root (vue instance) of the app in a child component?

Vue CLI Plugin Electron Builder dispatching vuex actions fails

I have a Vue Electron app created with Vue CLI Plugin Electron Builder and I try to integrate vuex, having the following store structure
import Vue from "vue";
import Vuex from "vuex";
import { createPersistedState, createSharedMutations } from "vuex-electron";
import user from "./modules/user";
const debug = process.env.NODE_ENV !== "production";
Vue.use(Vuex);
// eslint-disable-next-line no-console
console.log(user);
export default new Vuex.Store({
modules: {
user
},
plugins: [createPersistedState(), createSharedMutations()],
strict: debug
});
when I try to dispatch actions in App.vue
created() {
const userInDb = UserCotroller.getUser();
this.$store.disptach("setUser", userInDb);
}
I get
"TypeError: this.$store.disptach is not a function"
How do I use vuex in this setup?
you have a typo there:
created() {
const userInDb = UserCotroller.getUser();
this.$store.disptach("setUser", userInDb);
}
change this to:
created() {
const userInDb = UserCotroller.getUser();
this.$store.dispatch("setUser", userInDb);
}
you wrote disptach instead of the correct one dispatch

Vuex store initiated in mainjs but is undefined in App.vue

main.js:
import Vue from "vue";
import Axios from "axios";
import App from "./App.vue";
import router from "./router";
import store from "./store";
const axios = Axios.create({
baseURL: process.env.VUE_APP_BASE_URL
})
Vue.prototype.$http = axios;
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
when I try to use $store in App.vue it is undefined:
created() {
this.$store.dispatch('logout') // this.$store is undefined
}
store.js:
export default new Vuex.Store({
actions: {
logout({commit}) {
return new Promise((resolve, reject) => {
commit('logout')
localStorage.removeItem('token')
delete Vue.prototype.$http.defaults.headers.common['Authorization']
resolve()
})
}
}
}
Is it because it is not initiated in App.vue, because I can use at other vue components.
You haven't imported Vuex in Main.JS:
import Vuex from 'vuex'
Vue.use(Vuex)
Learn more about installing Vuex here
EDIT: Legit everyone just stole my answer...
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
// Options
});
And just put to the Vue Instance.
Hope it helps you.
First, you need to install Vuex using npm install vuex --save
Then, import it into your store.js.
To understand WHEN, WHY and HOW to use Vuex, refer this URL https://dev.to/napoleon039/when-why-and-how-to-use-vuex-9fl