我想设置可用的 <option>
之一标签为默认值。关于<select>
我正在使用的标签v-model
我知道 vue.js
文档对此进行了以下说明:
v-model
will ignore the ...selected
attributes found on any form elements. It will always treat the Vue instance data as the source of truth. You should declare the initial value on the JavaScript side, inside the data option of your component.
所以我正在使用 selected
带有 v-bind 的属性并直接传递 true
到它或通过数据选项中的变量。不幸的是它不起作用。这是一个jsfiddle .
这是示例代码:
HTML
<div id="app">
<select v-model="selectedData" @change="doSomething">
<option :selected="true" value="">
Please select account
</option>
<option
v-for="data in myData"
:key="data.id"
:value="data.val"
>
{{ data.val }}
</option>
</select>
{{ selectedData }}
</div>
JavaScript
new Vue({
el: "#app",
data: {
selected: true,
selectedData: null,
myData: [
{ id: 1, val: "abc" },
{ id: 2, val: "def" },
{ id: 3, val: "ghi" },
{ id: 4, val: "jkl" },
]
},
methods: {
doSomething: function(){
console.log('hello')
}
}
})
最佳答案
<select>
标签的模型是实际驱动下拉列表中所选项目的模型。
<select v-model="selectedData" @change="doSomething">
将“默认”选项更改为以下内容
<option value="-1">
Please select account
</option>
并且在您的数据对象中,而不是 null
分配给您在初始化时选择的值,将其设置为 -1
data: {
selectedData: -1,
myData: [
{ id: 1, val: "abc" },
{ id: 2, val: "def" },
{ id: 3, val: "ghi" },
{ id: 4, val: "jkl" },
]
},
关于javascript - Vue.js:通过 "selected"将 html <option> 标记设置为默认值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59586210/