Home > Back-end >  vuejs basic conditional rendering issue
vuejs basic conditional rendering issue

Time:05-07

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>

CodePudding user response:

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>

CodePudding user response:

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'

CodePudding user response:

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>
  • Related