How use an async function in Vue v-if?

Viewed 5915

I have a service that control the permissions, is something like this:

//service
async function isAdmin(){
    let user = await getUser();
    //other stuff
    return isAdmin;//true|false
}

//in main
Vue.prototype.$service = permissions;

//component
<template>
  <div>
    <h1 v-if="$service.isAdmin()">You are Admin</h1>
    <h1 v-else>You aren't Admin</h1>
  </div>
</template>

I tried including this in async function in the component, and as computed property, but doesn't work (ever returns a {} true), and seems some ugly.

There is a way to manage this?

1 Answers

The common practice to this kind of staff is to run the async operation in the mounted or created lifecycle hooks and update the data. Vue cookbook example for consuming data in async way.

<template>
  <div>
    <... v-if="isAdmin">
  </div>
</template>
<script>
export defualt {
  data(){
   return {isAdmin : null}
  }, 
  created: async function(){
      this.isAdmin = await this.$service.isAdmin()
  }
}
</script>
Related