Paulund

VueJS - Make API Requests With Vue Resource

When developing in JavaScript the majority of the ways you get data to show on the screen is through APIs, these will return JSON format of data and parsed by Vue to display content on the page. When developing with VueJS to access an API you have a few ways you can use normal JavaScript to make an ajax request to the API, you can use jQuery to make the API call, or you can use the Vue plugin Vue Resource to make web requests and handle the responses.

Installation

To install Vue Resource you have a number of options npm, bower or script CDN. ### npm


npm install vue-resource

Bower


bower install vue-resource

CDN


<script src="https://unpkg.com/[email protected]/dist/vue-resource.min.js"></script>

When this is installed you'll have an object attached to vue of http where you can access this by using Vue.http. ## Methods

After Vue Resource is install you have access to the following methods to make your API calls. - get(url, [options])

  • head(url, [options])
  • delete(url, [options])
  • jsonp(url, [options])
  • post(url, [body], [options])
  • put(url, [body], [options])
  • patch(url, [body], [options])

You will use this like following:


Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

Post Form Data

An example of posting form data is to use the JavaScript object FormData, this provides and easy to use key => value pairing object you can use to post the form data. In the below example we add the name and message from the Vue object to a new FormData object and then we can use this object in the body of the POST API request.


var formData = new FormData();

formData.append('name', this.name);
formData.append('message', this.message);

// POST /someUrl
this.$http.post('/someUrl', formData).then((response) => {
  // success callback
}, (response) => {
  // error callback
});

Now you can make API requests in your Vue projects. For more information about VueJS view the Github repo.