I have a Vue application with a series of checkboxes that add items to an array when the user selects a checkbox. There are about 6 items that could be selected, however, I need to reveal a <div>
if 2 specific items are selected:
Example array if all elements are checked:
["Apples", "Bananas", "Cucumbers", "Pears", "Peaches", "Strawberries"]
But, if ONLY Apples
and Pears
are checked AND/OR if Apples
OR Pears
are checked, I need to reveal a div
in the view with a set of instructions for the user.
I tried this but it didn't work:
<div v-if="(selectedProducts.length <= 2) && ( selectedProducts.includes('Apples') || selectedProducts.includes('Pears') )">
...show mycontent...
</div>
In my vue instance I have initiated the data like so:
data: {
selectedProducts: []
}
What's the correct way to write this logic? Should I use the array.every() method in this case? Thank you.
You could try
selectedProducts.indexOf('Apples') !== -1
Instead of
selectedProducts.includes('Apples')
If I understand correctly, you want to show the DIV if both apples and pears are selected and only two items are selected, or if one item is selected and the product is either apples or pears.
If that's true, here is a computed that does that.
computed:{
matched(){
let pears = this.selectedProducts.includes("Pears")
let apples = this.selectedProducts.includes("Apples")
if (this.selectedProducts.length === 2 && pears && apples) return true
if (this.selectedProducts.length === 1 && (apples || pears)) return true
return false
}
}
Working Example:
console.clear()
new Vue({
el: "#app",
data:{
products: ["Apples", "Bananas", "Cucumbers", "Pears", "Peaches", "Strawberries"],
selectedProducts: []
},
methods:{
onChange(evt, product){
if (evt.target.checked){
this.selectedProducts.push(product)
} else {
this.selectedProducts.splice(this.selectedProducts.indexOf(product), 1)
}
}
},
computed:{
matched(){
let pears = this.selectedProducts.includes("Pears")
let apples = this.selectedProducts.includes("Apples")
if (this.selectedProducts.length === 2 && pears && apples) return true
if (this.selectedProducts.length === 1 && (apples || pears)) return true
return false
}
}
})
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
<div v-for="product in products">
<label for=""><input type="checkbox" :value="product" @change="onChange($event, product)"> {{product}}</label>
</div>
{{selectedProducts}}
<hr>
<div v-if="matched">
Matched Criteria
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With