Use Axios for Remote Data Fetching with Vue Mounted Property

Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated a year ago

We'll see how we can use the mounted property of the configuration object to fetch data for our applications. We will set initial props and then have these updated with the returned data from our HTTP call.

Instructor: [0:00] In most cases, we're going to fetch data from an API and update our UI based on that data. Let's do that for our ticketTypes here. We're going to use the fetching library, Axios. Let's find out what package version that is.

[0:13] If we go to unpkg.com and if we search for Axios, it will give us the up-to-date version, so /distribution/Axios, we copy that URL. Back in our index.html, we're going to import that script. Now we can see that this is available as a global object that we can use on our code.

[0:31] Let's set our ticketTypes to an empty array, then we're going to add a mounted() function, and this function will be executed whenever the component has been mounted. At this point, we want to axios.get() and the URL to where I have my data. Once that's happened, we want to take the response and set this.ticketTypes to the response.

[0:56] Let's check our Vue application. We can see our root components. Our ticketTypes has those three objects in it. We don't have that mounted. Let's comment out that. We can see there are no ticket types. It's that empty array. We do have that. We fetch the data from GitHub and render our AUI based on that data.

Philip
Philip
~ 3 years ago

It would be great if a full URL was provided for the get to see it work locally. In the video the full URL is not visible.

Lucas Minter
Lucas Minter
~ 3 years ago

Hey Philip! I've found the github url I believe you were asking for.

Kevin Cunningham
Kevin Cunninghaminstructor
~ 3 years ago

Sorry for the delay! Lucas is exactly right, that's the file in question. However, this url responds with raw json: https://raw.githubusercontent.com/doingandlearning/vue-fundamentals/main/data.json

Hope that's helpful and sorry it wasn't clearer on the video!

Philip
Philip
~ 3 years ago

@Lucas @Kevin Thank you!! While it was clear what was going on in the lesson, it's still nice to see it in action locally ;)

DevMonks
DevMonks
~ 3 years ago

Thanks everyone! If you use this: 'https://raw.githubusercontent.com/doingandlearning/vue-fundamentals/main/data.json' the data will come in response.data so:

axios.get('https://raw.githubusercontent.com/doingandlearning/vue-fundamentals/main/data.json').then( response => this.ticketTypes = response.data )

Hope someone find this useful :)

Markdown supported.
Become a member to join the discussionEnroll Today