Warning from Vue: The computed property named 'axios' has already been defined in the data of the <App> component

Although similar questions may exist on Stack Overflow, I am still struggling to understand how to resolve this issue. I keep receiving the warning (as mentioned in the title) in my console.

https://i.sstatic.net/FtoFu.jpg

To reproduce the warning, use the following code snippet:

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

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

##App.vue

<template>
  <div class="TodoList">
    <p v-for="todo in todos" :key="todo.id">{{ todo.title }}</p>
  </div>
</template>

<script>
export default {
  mounted() {
    this.$store.dispatch("fillItems");
  },
  computed: {
    todos() {
      return this.$store.getters.todos;
    },
  },
};
</script>

<style>

</style>

##store.js

import { createStore } from 'vuex';

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

Answer №1

If you want to make axios accessible in any child component, you can add it to app.config.globalProperties:

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

In the child component, you can then use this.axios.

However, accessing axios inside the store context is a bit different because this refers to the store instance in actions. In this case, you should import axios directly into the store file and use it like this:

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))
        }
    }
})

Alternatively, you could assign axios to the store instance, but this is not recommended especially with typescript:

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

https://codesandbox.io/s/vue-3-ts-forked-q67kd?fontsize=14&hidenavigation=1&theme=dark

Answer №2

Utilizing the new features of Vue 3, you have the ability to create app globals for components through 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);  // Making it available to all components
app.use(store)
app.mount("#app")

Injecting

If using the options API:

export default {
  inject: ['axios'];   // Injecting in a specific component
}

When using the composition API:

const { inject } = Vue;
...
setup() {
  const axios = inject('axios');   // Injecting specifically where needed
}

Note: I jumped ahead with my response (thanks @BoussadjraBrahim), while you might not be inquiring about components, I'll keep that information here. If you simply need to utilize axios in a separate module, just import it as usual:

import axios from 'axios';

Then use axios instead of referring to it as this.axios

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is the responseText from XMLHttpRequest always stripped of tags in AJAX?

Whenever the server sends the XML string to the client using the XMLHttpRequest object, I noticed that when I insert the text inside the div tags, it appears without any tags. However, I actually need the XML tags to be present so that I can parse the cont ...

Navigating router queries within Nuxt: A step-by-step guide

One of the challenges I am facing is passing value parameters in my URL with the mounted function looking like this: mounted () { this.$router.push({ path: '/activatewithphone', query: { serial: this.$route.params.serial, machin ...

Exploring the Exciting World of Jquery Cycle and Dynamic Ajax Capt

Utilizing Jquery Cycle for image fading loaded by Ajax, along with displaying corresponding captions using the onBefore option in the plugin. The image transition is functioning perfectly, however, there seems to be a slight issue with the caption display. ...

Introducing Vuetify 3's v-file-input with interactive clickable chips!

I noticed an unexpected issue with the v-file-input component in Vuetify3. In Vuetify 2, it was possible to use the selection slot to customize the display of selected files. This functionality still works in both versions, as mentioned in the documentatio ...

Utilizing React to dynamically load JSON data and render a component

I am currently facing a challenge in rendering a React component that includes data fetched from a JSON using the fetch() method. Although the API call is successful, I am experiencing difficulties in displaying the retrieved data. Below is the code snip ...

How to incorporate global environmental variables into all SASS files in Nuxt.js

Is there a way to incorporate an environment variable into all my sass/scss files? This is what I have attempted in the nuxt.config.js file: export default { ... loaders: { scss: { data: '$myenv: ' + process.env.MY_ENV + ';&a ...

Invoke a PHP function within a Bootstrap Modal using AJAX technology

My webpage features a list of users generated through a PHP loop. By clicking on each user's name, a Bootstrap Modal appears showcasing more information about the user. The hyperlink for each user looks like this: <a href="#user" data-toggle="mod ...

Replace a function within the UI-Bootstrap framework

Incorporating the angular-bootstrap library into my app via bower has been a game changer. Although I am currently stuck with an (outdated) version that includes a pesky bug, upgrading is not yet feasible in my scenario. I considered inserting a customiz ...

Can you provide guidance on defining functions using standard syntax and incorporating children in React with TypeScript?

There are multiple ways to type it, such as using the interface React.FC<YourInterface> or explicitly declaring in an interface the type of children as JSX.Element or React.Node. Currently, my approach is: const MyComponent: React.FC<MyInterface& ...

An uncaught runtime error has occurred: TypeError - subSector.map is not a valid function

I'm encountering a challenge when attempting to map through JSON data retrieved from a fictitious API. The process works smoothly when there is more than one data item, but I encounter an error when there is only a single object. Below is the code sn ...

Hyphens make Tablesorter sort numeric fields uniquely

I have a table where data is displayed in the format of YYYY-####. Sometimes, there are values like 2012-456 and 2012-1234. By default, the sorting places 2012-1234 before 2012-456. If I change the sort to 'numeric', it disrupts the order of othe ...

RtcMulticonnection is not currently connected to any room

Trying to create a small video conference application, I developed a basic RTCMulticonnection app. However, it keeps sending repeated requests: https://rtcmulticonnection.herokuapp.com/socket.io/? userid=b1nxbxqjvhd&sessionid=mywebsite&msgEvent=RTC ...

Creating Awesome Icons in Kendo Grid with Code In this tutorial, we will learn how to programm

Looking to have a Kendo grid display a green fas-fa-clock icon if isActive is true, and a grey far-fa-clock icon if false. Clicking on the icon should toggle between true and false. Currently, the grid just shows the word true or false in the column. Cod ...

Are there any specific features in HERE maps for the JavaScript platform or REST API that pertain to rerouting functionality?

When a user deviates from the planned route, I am having trouble calculating an appropriate reroute. The calculateRoute service does not take into account the user's heading direction. I am attempting to implement the rerouting feature myself using J ...

Bind Vue.js 2 component's data property to the very first instance of the component or to a single instance only

Seeking assistance. I am relatively new to Vue.js and require some guidance. Scenario: I have a component with BS modal inside, which is rendered in a loop and has multiple instances. Problem: The first rendered component receives its data from the p ...

I am facing difficulties displaying the egin{cases}…end{cases} equation using Jekyll's MathJax

MathJax is used on our course website. We have implemented MathJax in Jekyll and hosted it on GitHub pages. While MathJax works well for simple equations, I have faced difficulties with more complex ones. Despite spending hours investigating and experiment ...

Styling the active selection in nav class with bold attribute in Bootstrap/AngularJs

How can I apply the bold attribute to the currently selected nav bar item? <ul class="nav"> <li role="presentation" ng-repeate="item in items" ng-class="{'active':navLink == item.header}"> </li> &l ...

Challenges with the Task List Board

I'm facing a bit of a challenge with this task. As a newcomer to JavaScript, I've set out on a quest to create a task list board where users can input tasks along with dates and times. The goal is for these entries to appear inside a photo using ...

Filling in the fields based on the data in the JSON

I prefer not to rely on jQuery for this task. If possible, I would like to maintain the presence of <mytag>. The JSON data structure I am working with is as follows: { "datas": [ { "id": "hotel_name", "value": ...

Control the HTML button's state according to the information received from the server

I am currently working with datatable Jquery and using an ajax call to retrieve data from the server. Let's assume that the database consists of three attributes: "Attribute1, Attribute2, Status". Depending on the Status attribute, I need to enable or ...