Vue.js:通过 "selected" 将 html <option> 标签设置为默认值不起作用
Vue.js: setting html <option> tag to default via "selected" doesn't work
我想将可用的 <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">
将您的 "default" 选项更改为以下内容
<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" },
]
},
您需要设置与 v-model
绑定的 属性 的初始值,因此 selectedData: ''
(而不是 null
)。我不确定我是否遗漏了其他东西,但我总是这样做。
我想将可用的 <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">
将您的 "default" 选项更改为以下内容
<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" },
]
},
您需要设置与 v-model
绑定的 属性 的初始值,因此 selectedData: ''
(而不是 null
)。我不确定我是否遗漏了其他东西,但我总是这样做。