0

i am working in a vuejs project and i am with a problem to check if a number is equal to an Array element. My code is this:

<div v-if="someValue != arrayElement">
   //
</div>

My problem is how i loop through the array to check if there is an equal value to the var 'someValue'.

1
  • 2
    equal to an Array element v-if="arrayElement.includes(someValue)" Commented Apr 28, 2020 at 14:26

2 Answers 2

2

You can use Array.includes(value) if you want to test an exact value

new Vue({
    data: function() {
        return {
            value: 3,
            array: [3,4,5,6,7,3]
        }
    },
    computed: {
        isInArray: function() {
            return this.array.includes(value);
        }
    }
})

Or directly in v-if directive like that

<span v-if="array.includes(value)"> {{ value }} </span>
Sign up to request clarification or add additional context in comments.

Comments

0

Better way is create computed property that filter your array by specific value. For example:

new Vue({
  data: function() {
    someValue: 3,
    array: [3,4,5,6,7,3]
  },
  computed: {
    arrayFiltered() {
      return this.array.filter(elem => elem === this.someValue);
    }
})

and in your html this may be look like this:

<div v-if="array.includes(someValue)">
   <div v-for="elem in arrayFiltered" :key="array.indexOf(elem)">
     {{ elem }}
   </div>
 </div>

So that way you can specify your array to be array of objects, for example

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.