Reputation: 87
I need to create condition in Vue for chcecking if array contains values.
items: { [1,5,8,12,63]}
<div v-for="item in items">
<div v-if="item == 1">
Yes
</div>
<div v-else>
No
</div>
</div>
And the output is: Yes, No, No, No, No .
I need to get only Yes and No one time. I need:
Yes, No.
Upvotes: 3
Views: 23318
Reputation: 7177
v-for
will just loop through the array and v-if
/v-else
will conditionally render the appropriate block of code for every item in the array. What you should do instead is use a method to check if a number is in your items
list. You can do that using indexOf
..
var app = new Vue({
el: '#app',
data: {
items: [1, 5, 8, 12, 63]
},
methods: {
itemsContains(n) {
return this.items.indexOf(n) > -1
}
}
});
<div id="app">
<div v-if="itemsContains(1)">
Yes
</div>
<div v-else>
No
</div>
</div>
You can also get rid of the method and do your conditional inline if you want ..
<div id="app">
<div v-if="items.indexOf(1) > -1">
Yes
</div>
<div v-else>
No
</div>
</div>
Upvotes: 8
Reputation: 13669
var app = new Vue({
el: '#app',
data: {
items: [1, 5, 8, 12, 63]
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<div v-if="items.indexOf(1) > -1">
Yes
</div>
<div v-else>
No
</div>
</div>
Upvotes: 5