Adding Axios to Quasar

One codebase, any platform!

If you’ve started out with Quasar CLI ‘s init function to create your project and forgot to enter the check in the box for Axios, no worries. This little tutorial will help you get Axios into your project.

Adding / Installing the Axios Module Package

Naturally, the first thing we’ll need to do is add the Axios package to our node modules. So, let’s do that. Enter the following in your console at your project’s root.

$ yarn add axios
$ npm install axios --save

You should end up with something like this, if all went well.

The console screen after a successful yarn addition of Axios.

Adding the Plugin File

Fortunately, we can stay in the console and use the new feature of the Quasar CLI.

1. Enter the following command into your console:

quasar new plugin axios

The command should have been carried out quickly, and you should see this in your console.

Before we follow the nice instructions given to us by the CLI to update quasar.conf.js, let’s go and add our plugin code.

2. With your code editor, open up the newly created axios.js file in the /plugin directory. The CLI command we just ran created that file for you. You should see this in the file:

The empty axios.js file example.

3. Go ahead and replace the code in that file with the following code.

import axios from 'axios' 
export default ({ Vue }) => {
Vue.prototype.$axios = axios

What did we do?

We’re importing the axios module, which we just installed above. Then we added the axios object(function) to the prototype of our Vue instance.

Note: If you need to access Axios outside of the Vue instance, for instance for using it with Vuex, you can alter this file accordingly. The Quasar docs demonstrates this clearly.

4. Let’s get back to what the CLI reminded us to do earlier. Open the quasar.conf.js file and go to the plugins entry at the top of the file and add axios as an array item for the plugins property. Your entry should look like this:

Axios entered as a plugin within quasar.conf.js

Save your changes and that’s it! Theoretically, you should now be ready to work with Axios. You can access Axios in your components like so:

this.$axios.get(... // or any other Axios method.

Please refer to the Axios documentation for more information about Axios.

And have fun with Quasar! 😃