选择选项默认值在加载时不显示,在选择其他选项时不显示



我使用vue.js设计了一个表单,其中1个元素是选项下拉列表。但是当加载时,默认值不会显示在下拉列表中选择的新目标时也不会显示。

使用v-for将所有选项从数组中循环,它运行并在单击时显示列表。但是在开始时没有显示默认值。

试图从这些链接中修复它:vue.js在@change上选择选项,将默认值设置为选项选择菜单

但没有成功

//DOM
<select
 v-on:change="selectSubject($event)"
 v-model="selectedSubject"
 class="form-control form-control-lg"
 id="selectSubject"
>
  <option value="" disabled>Choose subject</option>
  <option 
   v-for="(option, index) in subjectOption" 
   v-bind:value="option.value"
   v-bind:key="index"
  >
   {{ option.text }}
  </option>
</select>

//Logic
export default{
   name: "form-block",
   data: () => ({
      selectedSubject: null,
      subjectOption: [
         { text: 'Item 1', value: 'Item 1' },
         { text: 'Item 2', value: 'Item 2' },
         { text: 'Item 3', value: 'Item 3' },
         { text: 'Item 4', value: 'Item 4' },
         { text: 'Item 5', value: 'Item 5' },
      ],
   }),
   methods: {
     selectSubject (event) {
       console.log(event.target.value);
     }
   }
}

我只希望该值出现在默认值上,然后选择"选择新值"。

谢谢

您指定的默认值是 null,因此对于默认值,您应该做类似:

之类的事情
 data: () => ({
  selectedSubject: 'Item 1',
   ....
   })

模板中尝试以这种方式绑定值

v-bind:value="subjectOption[index].value" 
<select
 v-on:change="selectSubject($event)"
 v-model="selectedSubject"
 class="form-control form-control-lg"
 id="selectSubject"
>
  <option value="" disabled>Choose subject</option>
  <option 
   v-for="(option, index) in subjectOption" 
   v-bind:value="subjectOption[index].value"
   v-bind:key="index"
  >
   {{ option.text }}
  </option>
</select>

最新更新