Search code examples
vue.jscomboboxvuetify.js

Why doesn't combobox update edited item model?


Combobox is defined this way:

<template>
   <v-combobox
   clearable
   v-model="values"
   :items="items"
   item-text="name"
   ></v-combobox>
</template>

<script>
data () {
    return {
        items: [
            {"id": 2, "name": "tree"},
            {"id": 4, "name": "grass"},
            {"id": 5, "name": "freeze"},
            {"id": 9, "name": "moss"}
        ],
        values: ''
    },
    watch: {
        values () {
            console.log(this.values) // Output: {__ob__: Observer}: e.g. id: 2, name: tree
        }
    }
}
</script>

Combobox items are editable: I can select one of them (then the Observer is logged in the console), and edit it, but then nothing happens in the console.

How to update the model with edited entries?

EDIT: just discovered that the model gets updated when leaving the combobox field (onBlur). How to change this behavior to e.g. onKeyDown?

EDIT2: another discovery: when clicking outside the combobox, values get reset (undefined). So, only onChange event can be taken into consideration.


Solution

  • I figured out how to solve it, however I consider it rather as a non elegant workaround.

    To make things clear: I needed both id and name to be passed to the combobox. The id is read-only, while name entry has to be editable. id gets passed to the values model thanks to item-value="id" added to the combobox definition (it's already commented in discussion below Germano Buss Niehues' answer). name was only updated by the model when item was selected, but not after it was edited. And the edited value of name is the thing I needed.

    Eventually, I added the plain HTML id field to the combobox:

    <template>
       <v-combobox
         clearable
         id="words_names"
         v-model="values"
         :items="items"
         item-text="name"
       ></v-combobox>
    </template>
    

    and read the final value with:

    document.getElementById("words_names").value

    As I said, not very elegant but does its job...