Within my Vue application version 2.6.X, I utilize single-file components similar to the following structure:
<template>
<div>
<div v-if="users.length">
<!-- users list rendering here -->
</div>
<div v-else>
Warning: no users were found
</div>
</div>
</template>
<script>
import userService from '@/services/user-service'
export default {
name: 'UserList',
async created () {
this.users = userService.loadUsersFromServer()
},
data () {
return {
users: []
}
}
}
</script>
An issue arises where a brief "flash of invalid UI state" occurs after component rendering but before the users are loaded. Are there any recommended methods to prevent this undesired flash?
One solution involves introducing a loading
data prop, initializing it as true, then setting it to false once the AJAX request is complete. Subsequently adjusting the template as follows:
<template>
<div>
<div v-if="loading">
Users are loading, please wait....
</div>
<div v-else-if="users.length">
<!-- users list rendering here -->
</div>
<div v-else>
Warning: no users were found
</div>
</div>
</template>
While functional in this particular scenario, if multiple requests need to be awaited before displaying the UI, this approach could become complex. Is there an alternative method that is more straightforward and efficient?