Using Vue 3 and composition API with Setup syntax (TypeScript), I would like to declare a ref inside a component detailing informations of an user.
const userData: Ref<User | undefined> = ref({} as User)
if I use this syntax, I have to put all the time a "?" after userData when I want to access if because the data can also be undefined.
<template>
<div >
<HeaderPage :title="`Administrateurs - ${userData?.email}`" />
aaaa {{ userData }}
</div>
</template>
<script setup lang="ts">
import HeaderPage from '@/components/pages/Header.vue'
import { onMounted, ref } from 'vue'
import UserService from '@/api/modules/user'
import { useRoute } from 'vue-router'
import type { Ref } from 'vue'
import type { User } from '@/api/types/user.interfaces'
const route = useRoute()
const loading = ref(false)
const userData: Ref<User | null> = ref({} as User)
onMounted(() => {
fetchUserData()
})
function fetchUserData() {
UserService.getUser(route.params.userId as string).then((res) => {
userData.value = res
loading.value = false
})
}
</script>
EDIT tried this:
const userData: Ref<User> = ref()
CodePudding user response:
Allow userData to be undefined
const userData: Ref<User> = ref()
Only render the component when data is defined
<HeaderPage v-if="userData" :title="`Administrateurs - ${userData.email}`" />