Search code examples
javascriptvue.jsvuejs2

Vue JS do not show <p> if property is undefined


I have this markup on my template:

<div class="locButton" v-for="location in locResult.slice(0, 4)">
  <h5>{{ location.legal_name }}</h5>
  <p>{{ location.address1 }}<p>
  <p v-if="location.address2 !== undefined">{{ location.address2 }}</p>
  <p>{{ location.pri_phone }}</p>
</div>

But as result the element still gets printed like this on the DOM:

<div class="locButton">
   <h5>Name</h5> 
   <p>Address1</p>
   <p></p><!----> 
   <p>Phone</p>
</div>

What should I do on the v-if in order to not output the html <p> tag at all if that property is undefined or empty?


Solution

  • You have a typo on your first <p></p> tag

    <div class="locButton" v-for="location in locResult.slice(0, 4)">
      <h5>{{ location.legal_name }}</h5>
      <p>{{ location.address1 }}<p> <-- THIS NEED TO BE </p>
      <p v-if="location.address2 !== undefined">{{ location.address2 }}</p>
      <p>{{ location.pri_phone }}</p>
    </div>