Search code examples
javascriptvue.jsvue-componentmustache

How to display nothing when resource fails to load from the API in mustache in the context of vue.js


I'm new to Vue, so I want to know how to display a blank screen when the resource fails to load from the API. So below is the mustache that I have used in my program, wherein the variable is from the API.

<p class="text-2xl text-success">
    {{'+' + avgSwing.overall_performance + '%'}}%
</p>

So when the resource loads from the API, the output obtained is:

+36.14%

when the resource fails to load from the API, the output obtained is:

+undefined%

So, I'm expecting a blank screen instead of +undefined%, please help me with this. Thank you.


Solution

  • You can do this with v-if to conditionally show the <p> only when there is a response from the API:

    <p class="text-2xl text-success" v-if="avgSwing">
       {{ '+' + avgSwing.overall_performance + '%' }}
    </p>
    

    If avgSwing is not defined, the <p> tag is not added to the DOM.