Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value exists in vuejs

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..??

like image 711
b4dQuetions Avatar asked Dec 14 '22 08:12

b4dQuetions


2 Answers

From my point of view, the best way is:

<div id="looping" 
     v-for="display in editlistAssesments">
    <span v-if="typeof display.test_id !== 'undefined'">
        {{display.test_id}}
    </span>
</div>

Because if you use v-if="display.test_id" and the test_id value is 0 (boolean comparation) you will never see the display.text_id.

You can use also this another condition to check if is null or undefined: display.test_id != null (loose equality operator)

like image 102
tomloprod Avatar answered Dec 18 '22 08:12

tomloprod


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

like image 34
Alliswell Avatar answered Dec 18 '22 06:12

Alliswell