Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs showing evaluation v-if before data

Tags:

vue.js

vuejs2

Ok, the question is vague, but I have a code that looks like this:

<template>
  <div>
      <p v-if="users" v-for="user in users"> {{ user.name}} </p>
      <p v-else> No users found</p>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        users: null
      }
    },

    created() {
      var that = this 
      axios.get('...').then(response => {
          that.users = response.data
      }).catch(error => { .... })
    }
  }
</script>

So, the actuall script has no issues, it loads the users and shows it properly. But, always I see the No users founds before vuejs loads the users. I don't want to see that messages, unless users is null but it seems vue doesn't wait for that to be true before showing the v-else.

Is there any proper way to handle this

like image 793
hidar Avatar asked Jan 30 '23 12:01

hidar


1 Answers

Instead of using users for the if/else, use a loading property (you would probably need it anyway to present a loading state to the user):

<template>
  <div>
      <p v-if="!loading && users.length" v-for="user in users"> {{ user.name}} </p>
      <p v-else> No users found</p>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        users: null,
        loading: true
      }
    },

    created() {
      var that = this 

      axios.get('...').then(response => {
          that.users = response.data
          that.loading = false
      }).catch(error => {that.loading = false .... })
    }
  }
</script>
like image 162
Tomer Avatar answered Feb 05 '23 15:02

Tomer