Vue Js Make Ajax Call

Posted on  by admin
Asynchronous Javascript and XML (AJAX), is a way of communicating to a web server from a client-side application through the HTTP or HTTPS protocol.

Even though AJAX holds XML in the name, the way data is sent through requests or received doesn't have to be XML, but also plain text, or in most cases JSON, due to it being lighter and a part of JavaScript in and of itself. Vue.js is used as a front-end framework, and if you ever want to communicate with a server, to retrieve or store information to a database or perform some calculations on your data you will most likely need AJAX.

Even though AJAX can be used by creating an XMLHttpRequest object, which will be available through the browser. There are certain packages that can help us communicate with our server.

Vue.js has an official package which is called vue-resource which works as an HTTP client, but the official documentation suggests using Axios.

Axios is an HTTP client and it can be installed into our package.json dependencies via your package manager of choice, be it NPM or Yarn:.

After the installation, we can set up a minimalistic test component for demonstration purposes:.

Requests to a server over HTTP take a certain amount of time to return with a response, and, to make sure the information shown to the user is correct, promises will have to be used to make sure the data has returned before continuing with our code execution.

To use it in a component, we simply import the package and assign it to a variable:.
Generally, API calls are performed inside the mounted Vue lifecycle hook.
4

We are going to be using a mock JSON data service called JSONPlaceholder. This is a simulation for what a back-end endpoint will look like when hitting a REST API:.

In the code example above, the component is rendered before the information from JSONPlaceholder has arrived. Therefore, the usage of promises will make sure we can handle the data and add it to our view. The then() function, lets us manipulate our promise and tell our code what we are going to do if/when the request was successful.

We can, for example, with a callback function, check our response in the console:. A response has been returned, and we can see it inside the browser's console, but, how do we show the user the todos list?

We should hold the todos list inside the data object for future referencing inside the DOM.

PhilPhil
140k5

Not the answer you're looking for? Browse other questions tagged ajaxvue.jsasync-awaitarray.prototype.map or ask your own question.