Utilizing VueJS and VueRouter in my application has presented a challenge. The issue lies in the fact that static HTML elements within the Vue Component load before the data is fetched, resulting in empty forms and tables being displayed initially. I have implemented the fetch method within the created() lifecycle hook, however, this approach seems to be causing confusion for me. Below is an excerpt of my code:
<template>
<div id="app">
<h1>My Data length: {{fetchedData.length}}</h1>
<li v-for="value in fetchedData">{{value}}</li>
</div>
</template>
export default {
name: "MyVueComponent",
data() {
return {
fetchedData: [],
}
},
methods: {
async getData() {
await fetch('https://cli-vue-application.herokuapp.com/user/getUser', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
.then(function (response) {
return response.json();
}).then(function (data) {
this.fetchedData= data
}.bind(this));
}
},
created() {
this.getData();
}
}
The fetched data is correct, however, the h1 element displaying a length of "0" initially for a few seconds indicates that the fetch occurs after the static HTML is rendered.