Axios is a promise-based HTTP consumer library for each browsers and Node.js functions, which suggests it may be utilized in each frontend JavaScript functions and backend Node servers.
On this article, we are going to have a look at easy methods to use Axios in a easy Vue.js utility. Vue is an easy frontend JavaScript framework, so the Axios use case right here will likely be for the browser.
We are going to cowl:
Stipulations for this tutorial utilizing Axios with Vue.js
To comply with alongside, you’ll want to put in the next:
We’ll use npm as our JavaScript bundle supervisor, which is included if you set up Node.
Establishing our Vue.js venture
We are going to create our venture utilizing the Vue CLI, beginning by working the next command:
$ npm init [email protected]
This command prompts us with choices on how we want to arrange our venture.
I’ve chosen to call the venture mice-away
as a result of — you guessed it — we’re constructing a enjoyable cat-related app! We will even set it up to make use of TypeScript.
Right here’s a vue view (I couldn’t assist it 😅) of my venture configuration; be happy to vary yours as you favor:
Extra nice articles from LogRocket:
Axios gives entry to the totally different HTTP strategies by way of capabilities of the respective names. For instance, you may use .submit(…)
for POST requests, or you may use .get(…)
for GET requests, and so forth. Let’s have a look at choices for utilizing Axios for HTTP requests in our Vue venture!
Including Axios to our Vue.js app
We will set up Axios by working the next command:
$ npm i axios
Now that Axios is put in, we’ll have a look at two methods to make use of it in our venture.
Utilizing Axios with a easy import in your Vue.js part
You should use Axios in your Vue part by merely importing it within the part the place you must make an HTTP request. Right here’s an instance:
// AnimalFacts.vue <template> <div class="row"> <div class="col-md-12"> <h3>Cat Info</h3> </div> <div class="col-md-12"> <ul class="list-group"> <li v-for="(reality, index) in catFacts" :key="index" class="list-group-item">{{index + 1}}. {{reality.textual content}}</li> </ul> </div> <div class="row mt-3"> <div class="col-md-12 text-center"> <button @click on="loadMoreFacts" class="btn btn-md btn-primary">{{ fetchingFacts ? '...' : 'Load extra' }}</button> </div> </div> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' import axios from 'axios' interface AnimalFacts { textual content: string } export default defineComponent({ identify: 'AnimalFacts', information() { return { catFacts: [] as AnimalFacts[], fetchingFacts: false } }, strategies: { async fetchCatFacts() { const catFactsResponse = await axios.get<AnimalFacts[]>('https://cat-fact.herokuapp.com/details/random?animal_type=cat&quantity=5') this.catFacts = catFactsResponse.information }, async loadMoreFacts() [])) this.fetchingFacts = false }, async mounted() { await this.fetchCatFacts() } }) </script>
On this instance, we imported Axios in our part and used it inside one of many part strategies to fetch information for show on the web page by calling the GET
technique. You possibly can see the results of this technique under:
Utilizing Axios in our Vue.js venture by making a plugin
An alternative choice for utilizing Axios in our venture is to create a plugin and assign a worldwide Axios occasion to our venture. This selection is beneficial when you find yourself constructing an app to devour a particular API, which might be configured as the bottom URL.
Let’s create our Axios plugin!
First, we’ll create a listing to deal with our plugin by working the next in our terminal:
$ cd src/ $ mkdir plugins
Subsequent, we are going to create our Axios plugin file axios.ts
by working the next in our terminal:
$ contact axios.ts
Then, in our newly created axios.ts
file, we are going to create an Axios occasion and make it a worldwide property:
// axios.ts import axios from 'axios' import sort {App} from 'vue' interface AxiosOptions { baseUrl?: string token?: string } export default { set up: (app: App, choices: AxiosOptions) => { app.config.globalProperties.$axios = axios.create({ baseURL: choices.baseUrl, headers: { Authorization: choices.token ? `Bearer ${choices.token}` : '', } }) } }
Now, we are going to register our plugin to our Vue occasion in essential.ts
. Whereas registering our Axios plugin, we are going to go within the occasion choices, together with our baseUrl
:
// essential.ts import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' import router from './router' import axios from './plugins/axios' const app = createApp(App) app.use(createPinia()) app.use(router) app.use(axios, { baseUrl: 'https://cataas.com/', }) app.mount('#app')
Now that we’ve registered Axios, we’ve a worldwide Axios object accessible as this.$axios
. Let’s use it in our part:
// HomeView.vue <script setup lang="ts"> </script> <template> <essential> <div class="row"> <div class="col-md-12 text-center mb-3"> <span @click on="selectTag(tag)" v-for="(tag, index) in visibileTags" :key="index" class="badge rounded-pill fs-5 me-2" :class="[tag === activeTag ? 'text-bg-primary' : 'text-bg-secondary']"> #{{tag}} </span> <span @click on="showNext()" class="badge rounded-pill text-bg-light fs-4">...</span> </div> </div> <div v-if="https://weblog.logrocket.com/how-use-axios-vue-js/catImage" class="row"> <div class="col-md-12 text-center"> <img :src="https://weblog.logrocket.com/how-use-axios-vue-js/catImage" class="img-fluid" peak="500" width="450" :alt="activeTag ?? 'Default picture'"> </div> </div> </essential> </template> <script lang="ts"> import { defineComponent } from 'vue' import sort {AxiosInstance} from 'axios' declare module '@vue/runtime-core' { interface ComponentCustomProperties { $axios: AxiosInstance catTags: string[] } } interface DogBreed { identify: string } export default defineComponent({ identify: 'HomeView', information() { return { catTags: [] as string[], displayStart: 0, displayCount: 5, activeTag: '', catImage: '', }; }, computed: { cleanCatTags() { return this.catTags.filter((tag) => tag !== '').map((tag) => tag.change(/[&/#,+()$~%.'":*?<>{}]/g, '')) }, totalTags() { return this.cleanCatTags.size }, displayEnd() { const sliceEnd = this.displayCount + this.displayStart return this.totalTags > sliceEnd ? sliceEnd : this.totalTags }, visibileTags() { return this.cleanCatTags.slice(this.displayStart, this.displayEnd) }, hasNextTags() { return this.displayEnd < this.totalTags } }, strategies: { async fetchCatTags() { const tagsResponse = await this.$axios.get('/api/tags') this.catTags = tagsResponse.information }, showNext() { this.displayStart += this.displayCount this.selectTag(this.cleanCatTags[this.displayStart]) }, selectTag(tag: string) { const baseUrl="https://cataas.com/" this.catImage = `${baseUrl}cat/${tag}` this.activeTag = tag }, loadDefaultCatImage() { const baseUrl="https://cataas.com/" this.catImage = `${baseUrl}cat/gif` } }, async mounted() { await this.fetchCatTags() this.loadDefaultCatImage() }, }); </script>
In our part, we should overwrite the ComponentCustomProperties
sort to incorporate $axios
as a property. With out this, we’d get the next compiler error:
Property $axios doesn't exist on sort ComponentCustomProperties
In an effort to register $axios
, we should additionally set up Axios varieties by working npm i @varieties/axios
and importing the Axios occasion sort AxiosInstance
.
Within the fetchCatTags
technique of our HomeView
part, we used this.$axios
to fetch cat tags, with which we are able to show cat pictures.
The distinction between utilizing our plugin occasion and importing Axios immediately into our part is that with the plugin, we are able to configure choices for our Axios occasion to keep away from passing sure values for every request.
For instance, with our plugin, we don’t must go within the baseUrl
, and our request to /api/tags
resolves to the baseUrl
we configure.
You possibly can see the results of utilizing Axios with Vue by making a plugin under:
Conclusion
On this article, we tried out two methods of utilizing Axios in a Vue venture.
The primary possibility was importing the Axios object immediately into our part, which we used to fetch cat details from a cool cat details API.
Our second possibility was creating an Axios plugin that injected a worldwide Axios object. We additionally configured our Axios occasion’s base URL to a cat as a service API, which meant we didn’t must specify the complete URL in our requests.
You will discover the complete code used on this article in my Github repo.
I hope you discovered this text helpful. Please share any ideas or questions you might need within the remark part!
Expertise your Vue apps precisely how a consumer does
Debugging Vue.js functions might be tough, particularly when there are dozens, if not tons of of mutations throughout a consumer session. If you happen to’re thinking about monitoring and monitoring Vue mutations for all your customers in manufacturing, strive LogRocket. https://logrocket.com/signup/
LogRocket is sort of a DVR for internet and cell apps, recording actually all the things that occurs in your Vue apps together with community requests, JavaScript errors, efficiency issues, and rather more. As an alternative of guessing why issues occur, you may mixture and report on what state your utility was in when a difficulty occurred.
The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, supplying you with context round what led to an error, and what state the applying was in when a difficulty occurred.
Modernize the way you debug your Vue apps – Begin monitoring free of charge.