Search code examples
javascriptvue.jsquasar-frameworkv-model

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.

I have a multiple-select UI component, and a list of objects that I would like to display as the options. v-model will bind to the currently selected option.

Let's say I want to select an author from a list of authors. 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

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

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

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?


Solution

  • Use option-value and option-label to map options value and label to object keys.

    <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}`"
    />