I have the following component:
<template>
<div>
{{ componentData.symbol }}
</div>
</template>
<script setup>
const props = defineProps({
componentData: {
type: [Object, null],
required: true
}
})
</script>
When the app loads, componentData
will be set to null
, so componentData.symbol
will be generating an error because symbol
doesn’t exist inside componentData
. I could only render this component once componentData
is not null
, but for other reasons, it needs to be rendered even if it is null
. How would you go about handling this situation? How would you prevent the error?
2
Answers
Just add
?.
operator:You can render template parts conditionally:
Is the
componentData
variable is something that is being fetched from your server application? If so, you could, for example set a variableloading = true
and set it tofalse
in thecreated
life-cycle method once the data has been fetched.for example, your code could look something like that:
P.S.
Excuse my Vue 3.x skills, I work with Vue 2.x, but the idea is the same in both versions.