[Vuejs]-Show an info only if it exists with $auth and vuejs (nuxt)

0👍

The variable this.$auth.$storage.state.user is null.

Such as the v-if is on the email object or user, it throw error before checking the variable.

So, I suggest you to use this code:

<template>
  <div>
     <p v-if="this.$auth.$storage.state.user">{{ this.$auth.$storage.state.user.email }}</p>
  </div>
</template>

0👍

Actually If you consider the test cases, it will be like
this.$auth will be valid one but it might not contain $storage so it might throw an error saying Cannot read state of undefined. The same can be applicable when you go deeper checking for attributes.
So to do this kind of check at each stage you can follow the below approach

<template>
  <div>
     <p v-if="$auth?.$storage?.state?.user">{{ $auth.$storage.state.user.email }}</p>
  </div>
</template>

For optional chaining to work inside v-if,
install @babel/plugin-proposal-optional-chaining and add it to to your babel’s config plugins as @babel/plugin-proposal-optional-chaining

0👍

A simple solution that can work out of the box would be

<template>
  <div>
    <Navbar />
    <p v-if="isEmailFilled">
      {{ $auth.$storage.state.user.email }}
    </p>
  </div>
</template>

<script>
export default {
  computed: {
    isEmailFilled() {
      return this.$auth?.$storage?.state?.user?.email
    },
  },
}
</script>

Leave a comment