如果元素是 selected,如何检查 v-select

How check if v-select if element is selected

在 vuejs 中如何正确使用 if v-select 检查元素是否被选中 在带有 code/label 数组的选项数组中?

我试过 :

<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:
}

哪种方法有效?

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

您的代码没有正确测试 this.selection_filter_priority 是否为 null。要检查对象是否为 null,请改用 if (this.selection_filter_priority === null)

请看下面的演示:

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');
  }
}