我在模式中有一个下拉框,其中填充了设备对象。我想仅向用户显示每个设备对象的name
值。目前它正在这样做。但是当用户选择其中一个设备名称时,我想使用 v-model 来存储所选设备的 _id,而不是名称。我想要这个是因为如果我只有名称而不是 _id,后端必须做更多的工作。
这是模板:
<template>
<card-modal :visible="visible" @ok="buttonOK(selected)" @cancel="buttonCancel" :title="app.name" transition="zoom" :okText="'Add Device'">
<div class="block">
<p class="subtitle is-5">Choose a device to add to the app:</p>
<select v-model="selected">
<option v-for="device in devices">{{ device.name }}</option>
</select>
<span>Device: {{ selected }}</span>
</div>
</card-modal>
</template>
对我来说,保存整个设备对象(或仅保存 device._id)而不是仅保存用户选择的设备名称的最佳方法是什么?
最佳答案
您只需将 option
元素的 value
属性设置为每个对象的 _id
即可:
<select v-model="selected">
<option v-for="device in devices" :value="device._id">{{ device.name }}</option>
</select>
通过赋值 value 属性,会让 select 元素将此值作为选中的值。
看一个例子:
new Vue({
el: '#app',
template: `<div>
Selected: {{ selected }}
<select v-model="selected">
<option v-for="device in devices" :value="device._id">{{ device.name }}</option>
</select>
</div>`,
data() {
return {
selected: 1,
devices: [
{ _id: 1, name: 'Device 1' },
{ _id: 2, name: 'Device 2' },
{ _id: 3, name: 'Device 3' },
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
关于node.js - Vue.js,使用v-model从v-for获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58290320/