Bootstrap-Vue:在<b-form-select>中自动选择第一个硬编码的<option>

时间:2019-02-28 15:53:15

标签: bootstrap-vue

我正在将b-form-select与服务器端生成的选项标签一起使用:

        <b-form-select :state="errors.has('type') ? false : null"
                       v-model="type"
                       v-validate="'required'"
                       name="type"
                       plain>
            <option value="note" >Note</option>
            <option value="reminder" >Reminder</option>
        </b-form-select>

如果没有为此字段设置任何数据,我想自动选择列表中的第一个选项。

这可能吗?我还没有找到如何从Vue实例中访问组件的选项。

2 个答案:

答案 0 :(得分:2)

您的v-model应该具有第一个选项的值。

示例

<template>
  <div>
    <b-form-select v-model="selected" :options="options" />

    <div class="mt-3">Selected: <strong>{{ selected }}</strong></div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        selected: 'a',
        options: [
          { value: null, text: 'Please select an option' },
          { value: 'a', text: 'This is First option' },
          { value: 'b', text: 'Selected Option' },
          { value: { C: '3PO' }, text: 'This is an option with object value' },
          { value: 'd', text: 'This one is disabled', disabled: true }
        ]
      }
    }
  }
</script>

未设置任何数据时,您可以触发this.selected=${firstOptionValue}

答案 1 :(得分:0)

不知道第一个选项是什么。列表生成了吗?

如果您有动态数据,则可以执行类似的操作。

<template>
  <div>
    <b-form-select v-model="selected" :options="options" />
    <div class="mt-3">Selected: <strong>{{ selected }}</strong></div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      selected: [],
      options: [],
    };
  },
  mounted: function() {
    this.getOptions();
  },
  methods: {
    getOptions() {
      //Your logic goes here for data fetch from API
      const options = res.data;
      this.options = res.data;
      this.selected = options[0].fieldName; // Assigns first index of Options to model
      return options;
    },
  },
};
</script>