'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>
Solution 1:[1]
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>
Solution 2:[2]
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'
Solution 3:[3]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vavon |
| Solution 2 | Jeff Bowman |
| Solution 3 | Abdul Niyas P M |
