Starting Out With VueJS Part 2

/ Javascript / by Paul Robinson / 0 Comments

In this short bolt-on tutorial we are going to look at how to change where the data is coming from in our Film Watch list example. Instead of the data being hard coded into the Vue instance we are going to pull it in from a separate location using an AJAX request. Now creating a REST API is well beyond the scope of this tutorial so instead we are just going to put our data into a JSON file and request that.

If you haven’t read the first part of the Starting Out with VueJS I recommend you head back and read it now.

AJAX Request For Mr JSON

So first our data. I’ve expanded the data a little and placed it into a file called data.json (creative I know) and put that inside a folder called json in the root of our project. The data looks like this:

Now to request the data we could use jQuery’s AJAX methods, but we are going to use vue-resource instead. You can download it from the github repo or you can pull it from one of the many CDNs out there. Attach it to your document after Vue and you should be good to go.

Yes you can use browserify or webpack (etc), but to keep things simple and all about Vue we are just using bog standard script tags.

Now. We need to modify our original Vue instance to add remove our hard coded data and put in a placeholder for our external data.

Here you can see we have removed our data and replaced it with a boolean. This is to make sure whatever elements use the data as a conditional know it is empty when the page is first loaded. You could, if you wish, add a second variable to use as a loading indicator and set that to true any time your are loading the data. However, we are going to keep it simple here since the data only loads at page load and use the movies variable as an indicator as to if the data is loaded yet.

The second new part you may have noticed is the ready method. This is (in simple terms) triggered once Vue has attached to the $el and is ready to go, a great place to ask Vue to get our data. This is also where we get to use vue-resource. It should be pretty self-explanatory, we just ask it to grab the data from our JSON file and set the movies variable with the data. If there is an error we set an error variable we’ve added to the data property to true.

Wrapping Up

Now see if you can add in the elements for no movies being available & for there being an error. If you get stuck you can find the full modified HTML below.

That’s it. We are all done. You now have a Film Watch list that is pulling data from an external source. Soon we will take a look at how to build a simple REST API using Lumen (Laravel’s Micro Framework) and take our data from that and have changes persist by saving them back to the API. Look out for it soon.

Leave a Reply

Your email address will not be published. Required fields are marked *

I'll keep your WordPress site up-to-date and working to its best.

Find out more