skip to Main Content

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


  1. Just add ?. operator:

     <div>
        {{ componentData?.symbol }}
      </div>
    

    You can render template parts conditionally:

     <div v-if="componentData">
        {{ componentData.symbol }}
      </div>
    
    Login or Signup to reply.
  2. Is the componentData variable is something that is being fetched from your server application? If so, you could, for example set a variable loading = true and set it to false in the created life-cycle method once the data has been fetched.

    for example, your code could look something like that:

      <template>
      <div v-if="!loading">
        {{ componentData.symbol }}
      </div>
      <div v-else>
        <p>
          loading...
        </p>
      </div>
    </template>
    
    <script setup>
      let loading = true;
    
      const props = defineProps({
        componentData: {
          type: [Object, null],
          required: true
        }
      })
    
      onMounted(() => {
        this.loading = false;
      })
    </script>
    

    P.S.
    Excuse my Vue 3.x skills, I work with Vue 2.x, but the idea is the same in both versions.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search