Check if value exists in vuejs

b4dQuetions picture b4dQuetions · Mar 4, 2016 · Viewed 41.5k times · Source

I have data : 1,2,3,4,4,5 & my code like this:

<div id="looping" v-for="display in editlistAssesments">
  {{display.test_id}}
</div>

My code if in php such as like this

$temp_id = array();
foreach($data as $data){
  if(in_array($data ->test_id,$temp_id)){
    echo" 1: no";
    echo" 2: no";
    echo" 3: no";
    echo" 4: yes"; //because he have same value 
    echo" 5: no";
    $temp_id[] = $data ->test_id;
  }
}

how I can do that in loop vueJs..??

Answer

Alliswell picture Alliswell · Mar 9, 2016

As far as I understand, you want to check if value is in array and then render it accordingly?

If so, you need a Vue custom filter. Something like this will do the trick:

var vm = new Vue({
    el: 'body',

    data: {
        editlistAssesments: [1,2,3,4,4,5]
    },

    filters: {
        ifInArray: function (value) {
            return this.editlistAssesments.indexOf(value) > -1 ? 'Yes' : 'No';
        }
    },
});

And then use it like this:

<div id="looping" v-for="display in editlistAssesments">
    <span v-text="display.test_id | ifInArray"></span>
    <!-- bind Vue value to html element is better practice -->
</div>

Check docs for more information: http://vuejs.org/guide/custom-filter.html