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.
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.