VueJS2: How to check if array contains specific elements?

Viewed 28611

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.

4 Answers

Hi this should help you to find if a list have a certain element.

    if (cls.attributes.tags.includes("dance")) {
        console.log(cls.attributes.title);
      }
Related