Search code examples
vue.jsconditional-operatorvuetifyjs3

How to use ternary operator for function calls and button text in vuetify vue js 3?


I'm trying to have login button which toggles between icons "loginIcon/logoutIcon", tooltip toggles between Login/Logout and also the corresponding function onclick changes to login/logout.

I'm able to get this through v-if and v-else. But I want to use ternary operator for simplicity. But I'm not getting the expected results.

Here's the code using v-if and v-else

<template>
  <v-btn v-if="isLoggedIn" @click="logout">
    <template v-slot>
      <v-img :src="logoutIcon"></v-img>
      <v-tooltip activator="parent" v-if="tooltipsEnabled" location="bottom"> Logout </v-tooltip>
    </template>
  </v-btn>
  <v-btn v-else @click="login" variant="tonal" class="rounded-xl" style="width: 70px">
    <template v-slot>
      <v-img :src="loginIcon" width="16"></v-img>
      <v-tooltip activator="parent" v-if="tooltipsEnabled" location="bottom"> Login </v-tooltip>
    </template>
  </v-btn>
</template>

This is the code which I tried using ternary operator

<template>
  <v-btn
    @click="isLoggedIn ? logout : login">
    <template v-slot>
      <v-img :src="isLoggedIn ? loginIcon : logoutIcon"></v-img>
      <v-tooltip activator="parent" v-if="tooltipsEnabled" location="bottom">
        isLoggedIn ? "Login" : "Logout"
      </v-tooltip>
    </template>
  </v-btn>
</template>

Value of isLoggedIn is from store => const { isLoggedIn } = storeToRefs(useLoginStore()) And it changes inside the login/logout functions.

I don't see the expected behaviour for all these : Login/Logout tooltip change, login/logout function call change and the icon change.

What's wrong here?


Solution

  • It seems like you forgot to invoke it, for the function call, it should be:

    <v-btn @click="isLoggedIn ? logout() : login()">
    

    As for the text, you need to wrap them in {{}}:

          <v-tooltip activator="parent" v-if="tooltipsEnabled" location="bottom">
            {{ isLoggedIn ? "Login" : "Logout" }}
          </v-tooltip>