Vue HTTP requests

up:: Vue

POST

Using the built-in fetch() mehod:

fetch('https://url.com./data.json', {
	method: 'POST',
	headers: {
	},
	body: JSON.stringify({
		name: this.name,
		other: this.other,
	}),
});

GET

In the methods:

Using then:

fetch('https://url.com./data.json').then(function(response){
	if (response.ok) {
		return response.json();
	}
}).then(function(data) {console.log(data)}); 

(using await is probably easier)

  • You might need to transform the incoming data. Eg. from an object of objects to an array of objects.
  • It is also easier to use JavaScript Arrow Functions because inside them, this refers to the same as outside.
  • Using the Vue Instance Lifecycle of mounted(), you can load data on component mounting.

Loading spinner:

  • Add a data isLoading property
  • Update it throughout the methods. At the start: true. At the end, false.
  • Show loading message conditionally with v-if