【问题标题】:select option default value not show up when load & not show up when selected to other option加载时选择选项默认值不显示,选择其他选项时不显示
【发布时间】:2019-12-12 19:53:31
【问题描述】:

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

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

尝试通过以下链接修复它: Vue.js get selected option on @change, Set default value to option select menu

但没有成功

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

我只希望该值显示为默认值,然后在选择时更新为新值。

谢谢

【问题讨论】:

  • 我在编辑器中尝试了你的代码并且工作正常,默认值:selectedSubject:''
  • 嗨@kat,是的,我搞砸了让选项值从元素中消失的样式。

标签: javascript vue.js vuejs2


【解决方案1】:

您指定的默认值为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>

【讨论】:

  • 非常感谢您在这方面的帮助。我刚刚意识到我的 CSS 使元素消失。我在元素内放置了太多的填充。顺便说一句,我现在更清楚地了解您回答的逻辑。
猜你喜欢
  • 2020-06-19
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多