Johnson
Johnson

Reputation: 1526

How can I use multiple condition in v-if in VueJS?

Here is my code:

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>

This v-if=" item.FullName != null || item.FullName != '' " does not work, Why? How can I put two condition inside a v-if?

Upvotes: 44

Views: 146730

Answers (5)

Sean
Sean

Reputation: 547

You can create a computed property that evaluates all of the conditionals then have a single v-if for your computed property. It will make your template cleaner and the computed property will be self documenting.

Upvotes: 2

Samayo's answer is right, and maybe this question a little old, but there are some issues:

First, please avoid v-for with v-if in the same element! (source: https://v2.vuejs.org/v2/style-guide/#Avoid-v-if-with-v-for-essential)

And second, if you want to use v-if with || operator, just use a computed, or simple method.

Finally, I think its the better way if you use camelCase, not the PascalCase for the variants or for object's keys.

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

And if you use a method:

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

Upvotes: 10

samayo
samayo

Reputation: 16485

Maybe it's the way you are treating empty strings as false-ly values and || is saying: show fullname if any of the two (left/right) expressions are true, which is not what you want I think.

Try this instead:

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

Also, judging from your code, {{ FullName }} should be {{ item.FullName }}

Upvotes: 64

WS Chan
WS Chan

Reputation: 9

Simple and easy.

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

In Javascript, !!0 will return false, !!1 will return true, !!"" will return false, !!"a" will return trueand !!null will return false

Upvotes: 0

Mr CaT
Mr CaT

Reputation: 337

The best way is using computed stuff

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

and is it as condition

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

and instead of {{ FullName }} you should use {{ item.FullName }} You were almost right with condition, but error was because of {{ FullName }} that's why you should write {{ item.FullName }} and because of || instead you better might use && Also you can do the stuff like this:

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

Upvotes: 2

Related Questions