[Vuejs]-[Vue warn]: Computed property "axios" is already defined in Data. at <App>

2👍

You could add axios to app.config.globalProperties in order to access it inside any child component :

const app = createApp(App)
app.config.globalProperties.axios=axios

in child component use this.axios

but you couldn’t access it inside the store context because this in the actions refers to the store instance, so you should import axios inside the store file and use it like :

import { createStore } from 'vuex';
import axios from 'axios';
export const store = createStore({
    state: {
        todos: []
    },
    getters: {
        todos(state) {
            return state.todos
        }
    },
    mutations: {
        FILL_ITEMS(state, payload) {
            state.todos = payload
        }
    },
    actions: {
        fillItems({ commit }) {
            axios
                .get("https://jsonplaceholder.typicode.com/todos")
                .then(res => commit('FILL_ITEMS', res.data))
        }
    }
})

or you could assign axios to the store instance (It’s not recommended specially with typescript) :

const app = createApp(App)
store.axios = axios
app.use(store)
app.mount("#app")

Edit vue 3 ts (forked)

2👍

In Vue 3, you can create app globals for components using provide/inject:

Providing

import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'
import axios from 'axios';

const app = createApp(App)
app.provide('axios', axios);  // Providing to all components here
app.use(store)
app.mount("#app")

Injecting

In the options API:

export default {
  inject: ['axios'];   // injecting in a component that wants it
}

In the composition API:

const { inject } = Vue;
...
setup() {
  const axios = inject('axios');   // injecting in a component that wants it
}

Edit:
I answered too fast (thanks @BoussadjraBrahim), you’re not asking about components, but I’ll leave that answer too. If you just want to use axios in a separate module, you can use it like any import:

import axios from 'axios';

and use axios instead of this.axios

👤Dan

Leave a comment