Vue.js Condition: If contains

19,779

Solution 1

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>

See this JSFiddle

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>

Solution 2

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>
Share:
19,779

Related videos on Youtube

Peter Valek
Author by

Peter Valek

Updated on June 04, 2022

Comments

  • Peter Valek
    Peter Valek almost 2 years

    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.

    • Lahori
      Lahori over 5 years
      use array method i.e. [].includes(item) ? true : false