If the property is undefined, Vue JS will not display <p>

I am facing an issue with the following markup in 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>

However, when this is rendered on the DOM, it looks like this:

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

I need a solution for the v-if condition to ensure that the html <p> tag is not outputted at all if the property is undefined or empty.

Answer №1

There is a mistake in the first <p></p> tag you have used

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

Answer №2

Simply utilize this line of code:

<p v-if="location.address2">{{ location.address2 }}</p>

UPDATE:

Evidence that it is effective:

https://jsfiddle.net/1j6kn9uo/

Answer №3

The issue is quite straightforward, there's a missing closing tag for the p element in this line:

<p>{{ location.address1 }}<p>
. This causes the browser to close the p tag for location.address1 and open an empty <p></p> right after it. As a result, Vue renders <!----> because location.address2 is not defined.

Now that we've identified the problem, another optimization we can make is here:

<p v-if="location.address2 !== undefined">
. What does this mean? Well, there's no need to explicitly compare location.address2 with undefined. The v-if directive will evaluate to true as long as location.address2 is not null or undefined.

Take a look at the snippet below:

var app = new Vue({
  el: '#app',
  data: {
    location: {
      legal_name: 'Name',
      address1: 'Address1',
      pri_phone: 'Phone',
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h5>{{ location.legal_name }}</h5>
  <p>{{ location.address1 }}</p>
  <p v-if="location.address2">{{ location.address2 }}</p>
  <p>{{ location.pri_phone }}</p>
</div>

Answer №4

consider altering

<p v-if="location.address2 !== undefined">{{ location.address2 }}</p>

to

<p v-if="location.address2">{{ location.address2 }}</p>

Answer №5

While the solutions mentioned in other posts should generally work, there is another alternative that involves utilizing double logical NOT consecutively to explicitly coerce any value into a corresponding boolean primitive.

!!location.address2 // Guarantees boolean value -> True if it contains a value, false otherwise

Demo

new Vue({
  el: '#app',

  data() {
    return {
      location: {
        address1: 'Some address',
        address2: undefined
      }
    }
  },

  methods: {
    addAddress2() {
      this.location.address2 = 'Address 2';
    }
  }
})
#app>p {
  background-color: lavender;
  padding: 3px;
  margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <p>{{ location.address1 }}</p>
  <p v-if="!!location.address2">{{ location.address2 }}</p>

  <button @click="addAddress2">Add address 2</button>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Start progress bars on several divs that share a common class

I'm attempting to utilize the ProgressBar.js Plugin on multiple div elements that share the same class form-progress This is my HTML code: <div class="form-progress"></div> And here is the corresponding JavaScript code: var form_pr ...

Method for displaying or concealing list items with an onClick event in React without relying on JQUERY

I'm working on a feature to show/hide a specific <li> element. While I know this can be achieved with JQuery, I prefer not to mix actual DOM manipulation with React's virtual DOM handling. With that in mind, I have assigned each <li> ...

I'm currently experiencing a challenge with a project I'm tackling that specifically deals with chart.js

In my recent coding project, I created a script to gather user input and then present it in various chart formats. However, upon executing the code, the selected chart fails to display after inputting values and clicking on the "generate chart" button. Her ...

End event in NodeJS response does not activate

I'm encountering an issue with sending the response data to the client. The response is not being sent and the 'end' event is not triggered. I'm at a loss on how to resolve this issue. My objective is to send the retrieved data from red ...

What happens when `somevar` is `undefined` and resolved after `$q.all([somevar]).then(function(data)){};` is executed?

$q.all([promise]).then(function(data)){ console.log('resolved'); }; What happens when the promise is 'undefined' and gets resolved? Even if the promise is null or undefined, it still resolves. This behavior of $q is confusing me. Can ...

Mapping through multiple items in a loop using Javascript

Typescript also functions Consider an array structured like this const elementList = ['one', 'two', 'three', 'four', 'five'] Now, suppose I want to generate components that appear as follows <div&g ...

Vue has detected that the property or method "index" is being referenced in the render function, but it is not defined on the instance

<div class="input-wrapper" id="name" :data-text="name" :class="{ error: error.isErrorName }"> <input type="text" name="name" placeholder="Name…" @input="inputName($event.target.value)"> </div> data () { retur ...

My stored variable in the php session is not being recalled properly

Currently, my PHP script is generating new files based on user input. I want all documents to be created using the initial input to ensure consistency. In the first PHP script, I set the variable as follows: session_start(); $_SESSION["FirstName"] = $_POS ...

Choose only link-based criteria

I'm attempting to create a dropdown menu with links, but I only want to use parameters in the URL, not the entire file name. Below is the code snippet: <script type="text/javascript"> function goToNewPage(){ var url = document.getE ...

Using an image instead of a checkbox when it is selected (Angular 4/Ionic 3)

Is there a way to swap out the checkbox for an image? I want this image to change dynamically based on whether the checkbox is checked or not. Unfortunately, adding a class doesn't seem to do the trick as it modifies all icons in the same column. The ...

What could be the reason behind the child component updating without triggering a re-render in Reactjs?

I am encountering an issue with my main component and child chart component. Even though the main component updates the state of the child chart component upon connecting to a websocket, the chart does not redraw as expected. Interestingly, when I click on ...

What is the best way to eliminate mouse click release events?

Encountering an issue with my Vue/Vuetify Dialog that closes when clicking outside of it as expected. The problem arises when there is a text field inside the dialog. If I accidentally select the content and release the mouse outside of the dialog, it als ...

How can you set an input field to be initially read-only and then allow editing upon clicking a button using Vue.js?

//I have two divs that need to be set as readonly initially. When an edit button is clicked, I want to remove the readonly attribute and make them editable. <div> <input type="text" placeholder="<a href="/cdn-cgi/l/email-protection ...

Is it possible to include a submenu within a md-tooltip?

I have set up an md-tooltip for a sidebar, but I would like to enhance it by enabling a submenu option. For instance, if there is a Contacts submenu under the Profile menu, I want to be able to access Contacts when hovering over the Menu Icon. The tooltip ...

Looping through dates in a POST request using JavaScript/GAS - What's the best approach?

My task involves posting timesheet entries for the upcoming month into a system using an API. In order to do this, I require the following: User ID Assignable ID Dates (in the format YYYY-MMM-DD) Hours Initially, I obtained the user_id and assignable_id ...

Creating a custom login directive in Angular 2 and utilizing location.createComponent for dynamic

Incorporating a login system into my Angular app has been a priority for me lately. I came across a helpful resource here that outlines the process. However, I encountered an issue with the custom RouterOutlet directive as shown below: import { ElementRef ...

Identify differences between two arrays of varying sizes and filter out any identical elements

I am currently working with two JSON arrays: {"Array1":[ { "_id": "1234"}, { "_id": "5678"}, { "_id": "3456"} ]} as well as {"Array2":[ { "_id": "1234"}, { "_id": "5678"} ]} In my Node.js application, I am trying to find the differences be ...

Using Node.js for a game loop provides a more accurate alternative to setInterval

In my current setup, I have a multiplayer game that utilizes sockets for asynchronous data transfer. The game features a game loop that should tick every 500ms to handle player updates such as position and appearance. var self = this; this.gameLoop = se ...

Is there a possibility of Typescript expressions `A` existing where the concept of truthiness is not the same as when applying `!!A`?

When working with JavaScript, it is important to note that almost all expressions have a "truthiness" value. This means that if you use an expression in a statement that expects a boolean, it will be evaluated as a boolean equivalent. For example: let a = ...

Parameters in functions are received by value

When working with JavaScript, one common point of confusion is the way variables are treated based on their data type. Variables of primitives are passed by value, while variables of objects are passed by reference. However, in function arguments, both pri ...