hidar
hidar

Reputation: 5939

Vuejs showing evaluation v-if before data

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

Upvotes: 5

Views: 7848

Answers (2)

Quoc-Anh Nguyen
Quoc-Anh Nguyen

Reputation: 5056

I think this code is better:

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

<script>
  export default {
    data() {
      return {
        isLoaded: false,
        users: []
      }
    },

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

Upvotes: 1

Tomer
Tomer

Reputation: 17930

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>

Upvotes: 9

Related Questions