Problem
Im trying to load data from my database using vuejs + axios in a Laravel project. Locally I can make the request using axios and it returns the data, assigns it to variables and then outputs the data to the DOM.
When I push the same code to production the axios request takes a little longer to execute but it seems to be long enough that vuejs is ready before all the data is returned, leaving me with an annoying 'undefined property' error when the data attempts to be displayed. Sometimes this error persist's through 20+ refreshes before the data loads.
What I think the issue is
So my guess from reading up is that axios isn't getting the data as quickly as it should do so vuejs is ready to start serving the data but axios hasn't had a chance to collect it yet, resulting in the undefined error
What i've read and tried
I've read that using v-if statements on the objects that depend on the data should fix this issue. But it doesn't, all it does it hide the object from view if the data is not present. For Example...
HTML
<!-- If user.name exists, display user.name -->
<div v-if="user.name">
@{{ user.name }}
</div>
JAVASCRIPT
<script>
new Vue({
el: '#container',
data: {
user: {}
},
mounted() {
this.getUserData();
},
methods: {
getUserData(){
axios.post('/user/get').then((response) => {
// Check the response was a success
if(response.data.status === 'success')
{
this.user = response.data.user;
}
});
},
}
})
</script>
This doesn't work, it just doesn't display anything when the data hasn't been loaded yet.
Question
How do I ensure that my loaded data is displayed and not return an undefined error? The only way I can think is by allowing the user to 'click to retrieve data' on a failed attempt.
Further Information
Im not using vue templates, the child/parent structure or any vue libraries. I'm importing vue.js via CDN and using it on the page in a script as seen above. Im not sure if using it like this will cause any such limitations, i've only learnt vue.js on a basic and this works for the company and the boss...
user:nullandv-if=usershould work.