[英]Vue selected prop not working with v-model
當我使用v-model
進行select
時, :selected
道具沒有在 Vue2 中選擇目標option
:
模板
...
<select v-model="form.item">
<option :value="item.id" v-for="(item, index) in items" :selected="item.status == 2">{{ item.name }}</option>
</select>
...
腳本
data: function () {
return {
items: [{id:1, name: "foo", status: 1},{id: 3, name: "bar", status: 2}],
form: {item: null}
}
}
在這種情況下,安裝后沒有選擇的選項。
我怎樣才能解決這個問題?
筆記
當我刪除v-model
時它工作正常(默認選擇目標option
)但我在form.item
中沒有所選option
的值
v-model 將忽略初始值、選中或選中的屬性。 在任何表單元素上找到
解決方案是刪除 :selected 綁定。 並使用數據道具綁定到 v-model
<select v-model="form.selectedItem">
<option :value="item.id" v-for="(item, index) in items">{{ item.name }}
</option>
</select>
將 vue 實例聲明為
data() {
return {
selectedItem: 2
}
}
另一種解決方案是使用$refs
而不是 v-model。
<select ref="selectedItem">
<option v-for="(item, index) in items" :value="item.id" :selected="item.status == 2">
{{ item.name }}
</option>
</select>
然后要獲取所選項目的值,請調用...
this.$refs.selectedItem.value
<select v-model="selectedGroup">
<option :value="false" :selected="selectedGroup == false">All</option>
<option v-if="organization.groups" v-for="group in organization.groups" :value="group">{{ group }}</option>
</select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.