Search code examples
vuejs2v-select

How check if v-select if element is selected


How correctly in vuejs using if v-select check if the element is selected having in options array with code/label array?

I tried as :

<v-select 
  v-model="selection_filter_priority" 
  label="label" 
  :options="taskPriorityLabels" 
  id="filter_priority"
  name="filter_priority" 
  class="form-control editable_field" 
  placeholder="Select all"
></v-select>
console.log('-11 typeof this.selection_filter_priority::')
console.log(typeof this.selection_filter_priority)
console.log(this.selection_filter_priority)

if (typeof this.selection_filter_priority == 'object' && typeof this.selection_filter_priority != null) {
  filter_priority = this.selection_filter_priority.code // But if option is not selected(null) I got error here:
}

Which is the valid way?

"vue": "^2.6.10", "vue-select": "^3.2.0",


Solution

  • Your code didn't properly test if this.selection_filter_priority is null. To check if an object is null, use if (this.selection_filter_priority === null) instead.

    See the demonstration below:

    var nullValue = null;
    var objectValue = {};
    var numberValue = 1;
    
    console.log('null');
    check(nullValue);
    console.log('\n');
    
    console.log('object');
    check(objectValue);
    console.log('\n');
    
    console.log('number');
    check(numberValue);
    console.log('\n');
    
    function check(x) {
      if (x === null) {
        console.log('is null');
      }
    
      if (typeof x == 'object' && typeof x != null) {
      // is same as if (typeof x == 'object')
        console.log('null or object');
      }
      
      if (typeof x != null) {
        console.log('always true');
      }
    }