簡體   English   中英

Vue 選擇的道具不適用於 v-model

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM