What is the proper way to import Axios in Vue 3 once you have created a new project using the CLI?

When starting a new project, I used the command:

vue create hello-world

This generated essential files like HelloWorld.vue, app.vue, and main.js.

Next, I followed the documentation on Npm vue-axios to install Axios:

npm install --save axios vue-axios

In the main.js file, I imported Axios as follows:

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

However, when trying to use VueAxios according to its documentation:

const app = Vue.createApp(...)
app.use(VueAxios, axios)

I encountered a problem due to the difference in creating an app instance in Vue 3:

createApp(App).mount('#app')

So now I'm wondering how to correctly import axios. Any suggestions?

Answer №1

Utilizing createApp(App).mount('#app')
essentially performs the same function as:

import Vue from 'vue'
const application = Vue.createApp(App)
application.mount('#app')

// or
import { createApp } from 'vue'
const application = createApp(App)
application.mount('#app')

As per the guidelines laid out in Vue Axios's documentation, simply add the following line for application.use():

import { createApp } from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

const application = createApp(App)
application.use(VueAxios, axios) // 👈
application.mount('#app')

You may also concatenate it like this:

createApp(App).use(VueAxios, axios).mount('#app')

example

Answer №2

If you want to use only axios, you can import it and set it as a global property:

For bundlers like vue cli, vite or webpack:

import { createApp } from 'vue'
import axios from 'axios'
const app = createApp(...)
app.config.globalProperties.axios=axios

Now you can access it in any child component like this:

Using Option API:

this.axios.get(...)

For Composition API, it's recommended to import axios directly:

import axios from 'axios'

const MyComponent = {
  setup() {
    //use axios here

   .... 
  }
}

Alternatively, you can also use useAxios from the vueuse library (vue composition utilities):

import { useAxios } from '@vueuse/integrations/useAxios'
...
 setup() {
   const { data, isFinished } = useAxios('/api/posts')
 }

Answer №3

I found success with this in VueJS 3.

npm install vue-axios

import { createApp } from "vue";
import axios from 'axios'
import VueAxios from 'vue-axios'

const app = createApp(App);
app.use(VueAxios)
app.use(axios)

app.mount("#app");


this.axios.get(api).then((response) => {
    console.log(response.data)
})

For more information, check out the documentation: https://www.npmjs.com/package/vue-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

The process of ensuring a component updates upon clicking on it

In the process of creating a to-do app, I am working on implementing an edit mode for tasks. My goal is to have a task title that expands into task details when clicked (using Collapse from MUI). Additionally, I aim to enter into an edit mode by clicking o ...

Is it possible to use a full-width material-ui Button inside a Badge component?

Within a grid, I had initially used fullWidth on a Button to make it expand and fill the container. Everything was functioning correctly until I enclosed the Button in a Badge element. Now, the fullWidth property is not being applied, and the button rever ...

Create a polling feature using a Grease Monkey script

I am looking for a way to run a Tamper Monkey script on a Facebook page that regularly checks a database for new data and performs certain actions. I have attempted to implement polling using AJAX, and below is the code I used: (function poll() { setT ...

Utilizing memcache in conjunction with PHP and Node.js

Can JavaScript objects and PHP associative arrays be shared with memcache? Alternatively, is it necessary to convert the data into a string before sharing them? ...

Would you prefer to generate fresh HTML using JavaScript or dynamically load an existing HTML layout using AJAX?

I have a project where I need to generate a large amount of HTML that isn't currently on the page. Up until now, I've been using jQuery to construct the page piece by piece with JavaScript, adding divs and adjusting layouts as needed. Lately, I ...

Looking to streamline your webpack configuration in vue.config.js? Utilize webpack-chain for efficient setup. And, wondering how to leverage the speed-measure-webpack

Below is the setup in my vue-cli3 configuration file: vue.config.js: const path = require('path') const CompressionWebpackPlugin = require('compression-webpack-plugin') const SpeedMeasurePlugin = require("speed-measure-webpack-plugin" ...

An Iframe lacks the ability to showcase HTML content, unlike a browser which is capable of doing

I'm struggling to get my Iframe to show the html string properly. Here's the content of the string: var='<BODY style="MARGIN: 0px" bgColor=#ffffff marginwidth="0" marginheight="0"> <SCRIPT language=JavaScript> var Caller_User_Ty ...

Typescript's forEach method allows for iterating through each element in

I am currently handling graphql data that is structured like this: "userRelations": [ { "relatedUser": { "id": 4, "firstName": "Jack", "lastName": "Miller" }, "type": "FRIEND" }, { "relatedUser": ...

sole active component present

In my redux store, I have an array called rooms that is fetched from the server. In my component, I fetch this array from the store, map it, and display elements with the value of room['foo']. However, I am facing a problem where when a user clic ...

Enhance your webpage's body by zooming in using jQuery on Mozilla Firefox

I have a webpage and I would like to zoom its body when it loads using jQuery. However, the CSS zoom feature is not working in Mozilla Firefox. This is what I currently am using: $("body").css("zoom", "1.05"); It worked in Chrome, Opera, and Edge, but un ...

Receiving the latest state from Vuex in a Vue3 component

Is there a way to update the user state in Vuex and have it reflect instantly on the frontend without requiring a page reload? I've searched for solutions but haven't found any that work for me. I'm currently exporting the store as a functi ...

Origin Access-Control-Allow Not Recognized

Currently, I am developing a node.js app and have encountered a strange issue: This particular Angularjs snippet... // delete hosts $scope.delete = function(row) { var rowData = { hostname: row.hostname, ipaddr: row.ipAddress, ...

Issue with accessing Scope value in AngularJS directive Scope

FIDDLE I've recently developed a directive that looks like this: return { restrict: 'EAC', scope: { statesActive: '=' }, link: function (scope, element, attrs) { var ...

Stay dry - Invoke the class method if there is no instance available, otherwise execute the instance method

Situation When the input is identified as a "start", the program will automatically calculate the corresponding "end" value and update the page with it. If the input is an "end", simply display this value on the page without any modifications. I am in th ...

Is there a way to prevent the DOM from loading images until Angular has successfully injected the correct variables?

Having some trouble with this block of code I have: <div class="image" ng-repeat="image in images"> <img src="{{image.url}}"></img> </div> It seems that the image sources are being set correctly, but I keep getting an error wh ...

What are the steps to create a class diagram for a NodeJS application?

For my final year project, I am looking to develop an application using Node API. As we delve into drawing the class diagram, it occurs to me that unlike Java or C#, Node JS does not have a built-in class concept. What would be the most effective approac ...

What could be the reason for my failing express test?

I'm in the process of configuring a server using Node/Express and I want to write ES6 code, so I've incorporated babel into my setup. Currently, the server is operational, and I can successfully make the necessary requests. However, I am facing ...

How can I transmit information using Json and javascript?

Is there a way to utilize Json to collect data upon button press? I have tried using Javascript to create a function for the button, but I am struggling with integrating Json. Can anyone provide an example of how to achieve this? Below is the HTML code sn ...

Tips for Incorporating the YouTube Iframe API into Your ReactJS Project

While working in React, I am attempting to build a custom YouTube player component that includes a new set of player controls. The YouTube iframe API provides the following code snippet for creating a player instance: var tag = document.createElement(&ap ...

Discover the initial two instances of a specific element within a collection of javascript objects

Within my javascript arraylist, I am currently storing the following elements: list = [ {header: "header1", code: ""}, {label: "label1", price: 10}, {header: "header2", code: ""}, {header: "header3", code: ""}, {header: "header4", code: ""} ] My que ...