Nenad Kalicanin
Nenad Kalicanin

Reputation: 1

Why wont my div disapear ? v-if not working ! conditional rendering not working

<script setup lang="ts">
import type { KeycloakInstance } from 'keycloak-js'
import { inject, reactive } from 'vue'
import type { ICustomUser } from '../types/ICustomUser'
import useUserInfo from '../types/ICustomUser'
import { isDark, toggleDark } from '~/composables'

const keycloack = inject<KeycloakInstance>('keycloack')
const user = reactive<ICustomUser>(keycloack ? useUserInfo(keycloack.userInfo) : {})
function logout() {
  keycloack?.logout()
}
let userInfoVisible = false
function toggleUserInfoVisiblity() {
  userInfoVisible = !userInfoVisible
  console.log(userInfoVisible)
}
</script>

<template>
  <nav text-xl mt-6 inline-flex gap-2>
    <button class="icon-btn !outline-none" @click="toggleDark()">
      <div v-if="isDark" i-carbon-moon />
      <div v-else i-carbon-sun />
    </button>
    <button class="icon-btn !outline-none" @click="toggleUserInfoVisiblity()">
      <div i-carbon-api-1 />
    </button>
  </nav>
  <div v-if="userInfoVisible" class="contentArea">
    <h2 v-if="keycloack?.authenticated">
      ✔️ You are logged using keycloak
    </h2>
    <div>
      <h3>Full Name: {{ user.FullName }}</h3>
      <h3>First Name: {{ user.FirstName }}</h3>
      <h3>Last Name: {{ user.LastName }}</h3>
      <h3>Email: {{ user.isEmailVerified ? '✔️' : 'X' }} {{ user.Email }}</h3>
      <h3>Username: {{ user.Username }}</h3>
    </div>
    <button @click="logout">
      Logout
    </button>
  </div>
</template>

i have this vitesse-ligth with typescript and vue3 i use composition api i declared the userInfoVisible and the console shows that clicking the button changes the state,

but it wont change the dom element so the div is never shown the v-if is not working

pls help

Upvotes: 0

Views: 146

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Conditional rendering is working fine, but as your program has been set up, I don't see that you've made the userInfoVisible to be reactive, something which must be done explicitly when using the composition API.

To be specific,

let userInfoVisible = false`

should be

let userInfoVisible = ref(false)

after importing the ref function from vue, of course. Otherwise it is not reactive.

And

function toggleUserInfoVisiblity() {
  userInfoVisible = !userInfoVisible
  console.log(userInfoVisible)
}

should be

function toggleUserInfoVisiblity() {
  userInfoVisible.value = !userInfoVisible.value
  console.log(userInfoVisible.value)
}

Upvotes: 1

Related Questions