What is the best way to implement multiple conditions in v-if within VueJS?

Below is the code snippet I am working with:

JavaScript

let Names = [
    {
        Name: "Josh"
        FullName: ""
    },
    {
        Name: "Jonathan"
        FullName: null
    },
    {
        Name: "James"
        FullName: "James Johnson"
    }
];

Index.Vue

<ul>
    <li
        v-for="item in Names" 
        v-if=" item.FullName != null || item.FullName != '' "
    >
     {{FullName}}
    </li>
</ul>

The code

v-if=" item.FullName != null || item.FullName != '' "
seems to be ineffective. Can you explain why it's not working and suggest a way to include two conditions within a v-if statement?

Answer №1

Perhaps the issue lies in how you are handling empty strings as false values and using || to display fullname if either expression is true, which may not be your intended behavior.

Consider trying this approach instead:

<li v-for="item in Names" v-if="item.FullName !== null && item.FullName !== ''">

Furthermore, based on your code, it seems like {{ FullName }} should actually be {{ item.FullName }}

Answer №2

Jenny's response is spot on, even though this question may be a bit outdated, there are some important points to consider:

First of all, it is recommended to avoid using v-for with v-if in the same element! (source: https://v2.vuejs.org/v2/style-guide/#Avoid-v-if-with-v-for-essential)

Secondly, if you need to use v-if with || operator, it is best to utilize a computed property or a simple method.

Lastly, I believe it is preferable to use camelCase instead of PascalCase for variables and object keys.

<li v-if="checkIfFullNameExists(item)">
  <span>{{ item.fullName }}

If opting for a method:

methods: {
  checkIfFullNameExists (item) {
    if (![null, ''].includes(item.fullName)) return true
  }
}

Answer №3

To optimize your code, it is recommended to utilize computed properties.

computed: {
    condition() {
      this.FullName;
      return this.FullName !== null && this.FullName !== '';
    }
  }

This computed property can be used as a condition in your code.

<li v-for="item in Names" v-if="condition> 

Instead of using {{ FullName }}, make sure to use {{ item.FullName }}. The error was caused by referencing the wrong property. Additionally, consider using && instead of ||.

You can also improve your code like this:

 <li v-for="item in Names" v-if="item.FullName !== null && item.FullName !== ''> 

Answer №4

If you want to simplify your template and make your code more self-documenting, consider creating a computed property that evaluates all conditionals and then use a single v-if for that computed property. This approach will result in a cleaner template and easier-to-understand code.

Answer №5

Straightforward and uncomplicated.

<li v-for="item in Names" v-if="!!item.FullName>

When working with Javascript, !!0 will result in false, !!1 will result in true, !!"" will result in false, !!"a" will result in true, and !!null will result in false

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

Troubleshooting ActiveXobject Errors in JavaScript

I've implemented this script on my Default.aspx page. <script id="clientEventHandlersJS" type="text/javascript"> function Button1_onclick() { var locator = new ActiveXObject ("WbemScripting.SWbemLocator"); var s ...

Tips for assigning a cookie as the id of a div?

I've been tasked with making the selected menu stand out when the page is refreshed. I'm thinking of using a cookie to achieve this. Here's the HTML code: <div class="menuBar"> <div class="menuHeader ui-corner-top"> ...

I possess controller functions designed to remove a user from the system. My goal is to adhere to the DRY (Don't Repeat Yourself) principle by creating a dynamic response message for the JSON

I am looking to apply the DRY principle to my code snippet for deleting different types of users, and I also want to create a response that dynamically adjusts based on the model details provided to the find method. //The function below is responsible for ...

Unsure how to proceed with resolving lint errors that are causing changes in the code

Updated. I made changes to the code but I am still encountering the following error: Error Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. It is recom ...

In Vue, a computed property is rendered as regular text on the screen

Is there a way to format the title using HTML spans instead of plain text? Here is the code: spanTitle() { return this.title.replace(/([A-Za-z0-9'<>/]+)/g, '<span>$1</span>'); } {{ spanTitle }} this.title = "Upc ...

What is the process for dynamically looping through a table and adding form data to the table?

I am in the process of developing an hour tracking website that utilizes a form and a table. Currently, I have implemented the functionality where the form content gets added to the table upon the first submission. However, I need it to allow users to inp ...

Tips for swapping out the content within a "li" element

I am dealing with a situation where I have approximately 100 pages, all containing an <ul> tag, but the issue is that I need to enclose each list item within a <span> tag. Below is the code snippet I have tried: <ul style="list-style-type: ...

What is the best way to ensure that each link displays unique text in a separate div when clicked on?

<aside class="side_article_content"><p id="defaultText">Chakras are explained here.</p> <p id="baseChakraInfo" style="display:none;">Base Chakra details here.</p> <p id="sacralChakraInfo" style="display:none;">Sa ...

Use promises instead of directly calling res.json(data) when working with Node.js

When I make a post request to the payment_url, it triggers the second block of my function. Unfortunately, I am unable to retrieve any data in the then method because I am unsure how to pass the data back to the resolve function. Client-side call paypal. ...

Executing a Function in Another Vue Component (file)

Struggling to call a method from a different Vue component located in a separate file. I attempted using ref but encountered issues. As a newbie to Vue, any help with this task would be appreciated. Both components are stored in the same folder. The Defi ...

Is it possible to apply data filtering in a table by clicking on a specific segment of a pie chart within a Laravel Vue application?

After successfully implementing the click event for the chart to filter the data in the table, I am encountering an issue where not all the data in the table is returned when clicking outside the chart area. How can I ensure that all the data is returned w ...

The Bootstrap datepicker functions properly when used in plain HTML, but encounters issues when implemented within the .html()

Using HTML: <input class="m-ctrl-medium date-picker" size="16" type="text" id='lateETD1' name="dateRecv" value=""/> Not working with script: var ETD = $("#ETD"); ETD.html("<input class='m-ctrl-medium date-picker' id='la ...

Creating a JSON Array from a PHP Array with json_encode()

I have used the built-in json_encode() function to encode an Array that I created. I am in need of formatting it into an Array of Arrays as shown below: { "status": "success", "data": [ { "Info": "A", "hasil": "AA" }, { " ...

Retrieving a string from a variable, which was imported from JS, to use as a key within

Is it possible to assign a variable as the key of an object in JavaScript? I have imported constants from a 'definitions.js' file and I need to use these constants as keys: import * as cons from '../scripts/definitions.js' export def ...

Dynamically linking tabbable tabs is a useful technique that allows for

I have been working on an app that organizes websites into groups displayed as tabs in a tabbable navigator using Twitter Bootstrap. The idea is that each time a new group is added, a new tab should appear. Currently, this is how it looks: The functionali ...

Hovering over a thumbnail image triggers a popup in CSS3 or Jquery

Looking to showcase a collection of thumbnail images on a webpage with specific height and width dimensions? Wanting to implement a hover effect that displays a larger image in a fixed position within the wrapper at coordinates top:50px and left:50px? The ...

Is it possible to extract a string from a file and import the extracted string into another file using require() in NODE.js?

My file structure looks like this: collegesapp ├── node_modules │ ├── express │ ├── connect │ ├── jade │ └── passport ├── routes │ └── routes.js ├── views │ ├── index.jade │ ...

Dynamic item addition feature activated by button on contact form

I am looking to create a form that includes the standard name, phone, email fields as well as a dropdown for selecting products and a text box for inputting quantity. The unique aspect is allowing users to add multiple products (dropdown and quantity textb ...

Creating a nested tree structure array from a flat array in Node.js

I have an array structure that I need to convert into a tree array using node.js. The current array looks like this: var data= [ { "id1": 1001, "id2": 1002, "id3": 1004, ... } ...

Is there a way to implement DnD functionality on a dynamically generated div element within an HTML page using Dojo

Is it possible to implement drag and drop functionality on dynamically generated div elements using Dojo? I have experimented with various methods to incorporate this feature. Below is a snippet of my code: var inputdiv = document.createElement('div& ...