[英]Use a display value while preserving v-model binding in Vue
Sorry if this one is simple, but I just can't figure it out.对不起,如果这个很简单,但我就是想不通。 I'm using Quasar Framework, but I think this is more of a Vue issue.
我正在使用 Quasar Framework,但我认为这更像是一个 Vue 问题。
I have a multiple-select UI component, and a list of objects that I would like to display as the options.我有一个多选 UI 组件,以及一个我想作为选项显示的对象列表。
v-model
will bind to the currently selected option. v-model
将绑定到当前选择的选项。
Let's say I want to select an author from a list of authors.假设我想 select 来自作者列表的作者。 The component call looks like this:
组件调用如下所示:
<q-select
v-model="currentAuthor"
:options="authors"
label="Select an Author..."
/>
The issue is that authors
contains objects, not strings, for example问题是
authors
包含对象,而不是字符串,例如
this.authors = [
{ first_name: 'Roald', last_name: 'Dahl', id: 1},
{ first_name: 'J.R.', last_name: 'Rowling', id: 2},
]
Using v-model
with the raw object just displays entries in the dropdown with the value将
v-model
与原始 object 一起使用只会在下拉列表中显示带有值的条目
[object Object]
on each.在各个。
I don't want to map the authors array of objects to an array of strings, because when selected, I need the id
attribute from each.我不想将作者对象数组 map 转换为字符串数组,因为选择时,我需要每个对象的
id
属性。
How can I set a display value for the dropdown (something like ${author.first_name} ${author.last_name}
) while still binding to the object with v-model
?如何在仍然使用
v-model
绑定到 object 的同时为下拉菜单设置显示值(类似于${author.first_name} ${author.last_name}
)?
Use option-value
and option-label
to map options value and label to object keys.将
option-value
和option-label
用于 map 选项值,将 label 用于 object 键。
<q-select
v-model="currentAuthor"
:options="authors"
label="Select an Author..."
option-value="id"
:option-label="(item) => item === null ? 'Null value' : `${item.first_name} ${item.last_name}`"
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.