4
votes

I'm trying to dynamically set the value of a text field in Vuetify, focus it and selecting its text (in order for the user to be able to quickly reset the field if necessary). The error I get is "select is not a function". This works for normal text inputs, but does not with Vuetify text fields.

<template>
    <vContainer>
        <vTextField
            ref="input"
            v-model="input"
        />
        <vBtn
            @click="test"
        >
            Select
        </vBtn>
    </vContainer>
</template>

<script>

export default {
    data: () => ({
        input: null,
    }),

    methods: {
        test() {
            this.input = 'test value';
            this.$refs.input.focus();
            // this.$refs.input.select(); -> TypeError: this.$refs.input.select is not a function
        },
    },
};

</script>
2

2 Answers

7
votes

The problem is that this.$refs.input is not the underlying HTML input element. To get the input element do something like...

let inputEl = this.$refs.input.$el.querySelector('input')

Also, setting the this.input value and then attempting to immediately focus() and select() will not work. You'd need to use nextTick or setTimeout before attempting to select(). For example:

  test() {
        let inputEl = this.$refs.input.$el.querySelector('input')
        this.input = 'test value'
        setTimeout(()=>{
            inputEl.select()
        },200)
  },

Demo

4
votes

An easy trick to select text in text field:

<v-text-field
    v-model="inputModel"
    @focus="$event.target.select()"
></v-text-field>