使用v-for使用对象生成选择选项

sen*_*nty 2 vue.js vue-component vuejs2

我有一个包含此结构中的用户名的对象:

clients: {
   1: {
     first_name:"John"
     last_name:"Doe"
     middle_name:"A"
   },
   2: {
     first_name:"Jenny"
     last_name:"Doe"
   },
}
Run Code Online (Sandbox Code Playgroud)

我想在选择输入中循环它们作为选项

<option v-for="(value, client, index) in clients" :value="">{{ value }}</option>
Run Code Online (Sandbox Code Playgroud)

我来到这里,但我无法弄清楚如何正确组织字符串.也许,有没有办法在计算属性中解析它,所以我可以有空间放置代码?

如果我可以使用这样的东西,我认为它会起作用,但也无法弄清楚如何做到这一点.

computed:{
    clientNameOptions() {
        for (const key of Object.keys(this.clients)) {
            return `<option value="` + this.clients[key].first_name + ' ' + this.clients[key].middle_name + ' ' +
             this.clients[key].last_name + `"></option>`
        }
    }
 }
Run Code Online (Sandbox Code Playgroud)

实现它的正确方法是什么?

Ber*_*ert 9

这主要是猜测你想要什么,但你可以使用计算属性构建你的选项.

console.clear()


new Vue({
  el:"#app",
  data:{
    clients: {
      1: {
        first_name:"John",
        last_name:"Doe",
        middle_name:"A"
      },
      2: {
        first_name:"Jenny",
        last_name:"Doe"
      },
    },
    selectedClient: null
  },
  computed:{
    options(){
      return Object.keys(this.clients).map(k => {
        let o = this.clients[k]
        return `${o.first_name} ${o.middle_name ? o.middle_name : ''} ${o.last_name}`
      })
    }
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
   <select v-model="selectedClient">
     <option v-for="option in options" :value="option">{{option}}</option>
   </select>
  <hr>
  Selected: {{selectedClient}}
</div>
Run Code Online (Sandbox Code Playgroud)