Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear v-autocomplete as soon as a value has been selected

Tags:

vuetify.js

I'm trying to do the following with the v-autocomplete component:

  1. The user selects a value in the v-autocomplete component
  2. As soon as a value have been selected, I save the value in a lastModel property
  3. I want to clear the v-autocomplete value in order to allow the user to continue typing another value.

Problem is: I can't clear the v-autocomplete component as soon as I select a value.

Here is the basic markup I wrote to illustrate what I want:

<v-autocomplete
   v-model="model"
   :items="states"
   label="Where do you live"
   @change="modelChanged"
   ref="autocompleteComponent"
/>

And the JS:

new Vue({
    data () {
        return {
            model: null,
            lastModel: null,
            states: [
                'Alabama', 'Alaska'
            ]
        }
    },
    methods: {
        modelChanged () {
            // We don't want lastModel to update if model is null
            if (this.model) {
                this.lastModel = this.model
            }
            this.model = null
        }
    }
})

So that does not work. However, if I wait one second in order to reset the model, it works:

new Vue({
    data () {
        return {
            model: null,
            lastModel: null,
            states: [
                'Alabama', 'Alaska'
            ]
        }
    },
    methods: {
        modelChanged () {
            if (this.model) {
                this.lastModel = this.model
            }
            setTimeout(() => {
                this.model = null
            }, 1000)
        }
    }
})

However, waiting a second is not a solution I like, and I would love to know how to write this better, in order to make it more "native"

Here is a codepen to try it out: https://codepen.io/anon/pen/qyKdaZ?editors=1011

like image 837
Hammerbot Avatar asked Aug 03 '18 10:08

Hammerbot


1 Answers

replace setTimeout with this.$nextTick

this.$nextTick(() => {
    this.model = null
})
like image 85
Traxo Avatar answered Oct 16 '22 18:10

Traxo