使用 Vuetify 在 textField 中选择文本

Pas*_*aud 4 vue.js vuetify.js

我正在尝试在 Vuetify 中动态设置文本字段的值,将其聚焦并选择其文本(以便用户能够在必要时快速重置该字段)。我得到的错误是“选择不是函数”。这适用于普通文本输入,但不适用于 Vuetify 文本字段。

<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>
Run Code Online (Sandbox Code Playgroud)

icl*_*126 14

在文本字段中选择文本的简单技巧:

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


Zim*_*Zim 7

问题在于这this.$refs.input不是底层的 HTML 输入元素。要获取输入元素,请执行以下操作...

let inputEl = this.$refs.input.$el.querySelector('input')
Run Code Online (Sandbox Code Playgroud)

此外,设置该this.input值然后立即尝试focus()select()不会起作用。在尝试之前,您需要使用 nextTick 或 setTimeout select()。例如:

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

演示