Vzupo
Vzupo

Reputation: 1478

vuejs basic conditional rendering issue

I simply just want to show the span if the name is found in the data. If its not found in the data, I want the span to hide. I am using simply v-if or v-else.It is currently displaying "my name is in the data". But it is not. I basically will have some names...and want the "my name is in the data" to only display if the name is indeed there.

new Vue({
  el: "#app",
  data: {
    FirstName:'Paul',
   
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

 <span v-if="FirstName=='lu'||'John'||'Sue'">
  My Name is in the data
 </span><br>
 <span v-else>
   Not available
 </span>
</div>

Upvotes: 0

Views: 64

Answers (3)

user459872
user459872

Reputation: 25039

You can also use Array.includes in your v-if condition to check whether FirstName is in any set of values.

<span v-if="['lu', 'John', 'Sue'].includes(FirstName)">
  My Name is in the data 
 </span>
 <span v-else>
   Not available
 </span>

Upvotes: 0

Jeff Bowman
Jeff Bowman

Reputation: 95784

In Javascript, non-empty strings are regarded as true ("truthy") in boolean expressions, and equality is of a higher operator precedence than boolean OR (||). Therefore, as a boolean, your expression reads as though it were:

(FirstName=='lu') || true || true

The above expression is always true, so your element is always visible.


As in Vavon's answer, you'll need it to read:

FirstName=='lu'||FirstName=='John'||FirstName=='Sue'

or with spaces:

FirstName == 'lu' || FirstName == 'John' || FirstName == 'Sue'

Upvotes: 0

Vavon
Vavon

Reputation: 26

I think it's better to do your conditionals like this

new Vue({
  el: "#app",
  data: {
    FirstName:'Paul',
   
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

 <span v-if="FirstName=='lu'|| FirstName=='John' || FirstName=='Sue'">
  My Name is in the data
 </span>
 <span v-else>
   Not available
 </span>
</div>

Upvotes: 1

Related Questions