Search code examples
javascriptvue.jscomboboxvuetify.js

Problem with updating model in Vuetify combobox


i'm having problems with the v-combobox. (see Code Example).
The problem occurs if i do the following:

  1. Enter a string into the combobox
  2. Click the save button before the combobox is unfocused.
  3. The method save() is executed
  4. The console.log() returns the previous value and not the actual one.

How can i get the actual value of "value" during the execution of the save command?

<template>
  <v-app>
    <div id="app">
      <v-card>
        <v-card-text>
          <v-container>
            <v-combobox v-model="value" label="write"></v-combobox>
          </v-container>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn text color="secondary" @click="save">save</v-btn>
        </v-card-actions>
      </v-card>
    </div>
  </v-app>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      addDialog: "false",
      value: ""
    };
  },
  methods: {
    save() {
      console.log(this.value);
      this.addDialog = false;
    }
  }
};
</script>

Solution

  • So let's start with what's done correctly:

    1. Your combobox is correctly v-modelled to your value data variable.
    2. You are referencing the data variable correctly in your save() method.

    However, with a combobox, the default behaviour is that the v-model variable is not actually updated until the you lose focus on the input. If you try with your above code, writing something in the combobox, then clicking/tabbing out of it, and then clicking save, it should work as you expect.

    In order to get this to automatically work we can actually lose focus of the combobox within save(), by using the blur method.

    Firstly, add a ref to your combobox. Then, call the blur method on this ref as the first thing you do in your save function. Finally, we need to use nextTick to ensure that value has been completely updated, before trying to console.log it. The updated parts of the code look like this:

    <v-container>
        <v-combobox v-model="value" ref="myComboBox" label="write"></v-combobox>
    </v-container>
    
    ...
    
    save() {
        this.$refs["myComboBox"].blur();
        this.$nextTick(() => {
            console.log(this.value);
            this.addDialog = false;
        });
    }