我使用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);
}
}
}
我只希望该值显示为默认值,然后在选择为新值时进行更新。
谢谢
答案 0 :(得分: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>