如何在 Vue3 中使用 v-for 创建带有选定选项的下拉列表?

How to create a droptdown list with a selected option usion v-for in Vue3?

我想使用 Vue3 从以下数据生成一个下拉列表

{
  "ResourcesTypes" : [
    { 
      "label": "Sites",
      "uri": "http://example.org/edytem#Site"
    },
    { 
      "label": "Oeuvres",
      "uri":  "http://patrimalp.org/brocarts/onto#Oeuvre",
      "selected" : true
    },
    {
      "label": "Brocarts",
      "uri": "http://patrimalp.org/brocarts/onto#Brocart"
    }
  ]
}

生成下拉列表的模板是

<template>
  <div class="dropdown">
    <select v-model="selected" @change="onChangeMethod($event)">
      <option disabled value="">Sélectionnez le type de ressources</option>
      <option v-for="resourceType in resourcesTypesData.ResourcesTypes" :key="resourceType.uri"
        :value="resourceType.uri"
        :selected="resourceType.selected" 
       >
         {{ resourceType.label }}
       </option>
    </select>
  </div>
</template>

我希望在选择第三个选项 (Oeuvre) 后得到以下 HTML 结果

<select>
   <option disabled="" value="">Sélectionnez le type de ressources</option>
   <option value="http://example.org/edytem#Site">Sites</option>
   <option value="http://patrimalp.org/brocarts/onto#Oeuvre" selected>Oeuvres</option>
   <option value="http://patrimalp.org/brocarts/onto#Brocart">Brocarts</option>
</select>

但我得到的是:

<select>
   <option disabled="" value="">Sélectionnez le type de ressources</option>
   <option value="http://example.org/edytem#Site">Sites</option>
   <option value="http://patrimalp.org/brocarts/onto#Oeuvre">Oeuvres</option>
   <option value="http://patrimalp.org/brocarts/onto#Brocart">Brocarts</option>
</select>

但是如果将 :selected 替换为 :foo 我会得到预期的结果。 为什么不考虑 selected 属性?

您可以将您选择的选项设置为 v-model:

const app = Vue.createApp({
  data() {
    return {
      resourcesTypesData: {
        "ResourcesTypes" : [{"label": "Sites", "uri": "http://example.org/edytem#Site", "selected" : false }, {"label": "Oeuvres", "uri":  "http://patrimalp.org/brocarts/onto#Oeuvre", "selected" : true
 }, {"label": "Brocarts", "uri": "http://patrimalp.org/brocarts/onto#Brocart", "selected" : false}]},
      selected: null
    }
  },
  computed: {
    select() {
      return this.resourcesTypesData.ResourcesTypes.find(r => r.selected).uri
    }
  },
  mounted() {
    this.selected = this.select
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div class="dropdown">
    <select v-model="selected" @change="onChangeMethod($event)">
      <option disabled value="">Sélectionnez le type de ressources</option>
      <option v-for="resourceType in resourcesTypesData.ResourcesTypes" :key="resourceType.uri"
        :value="resourceType.uri"
       >
         {{ resourceType.label }}
       </option>
    </select>
  </div>
</div>