3

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.

1
  • 2
    use array method i.e. [].includes(item) ? true : false Commented Oct 14, 2018 at 13:49

2 Answers 2

8

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>
Sign up to request clarification or add additional context in comments.

Comments

5

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.