Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use an async function in Vue v-if?

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?

like image 441
Koronos Avatar asked Mar 06 '23 02:03

Koronos


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>
like image 177
elad frizi Avatar answered Mar 09 '23 07:03

elad frizi