【问题标题】:Selecting text in a textField with Vuetify使用 Vuetify 在 textField 中选择文本
【发布时间】:2020-06-16 11:05:49
【问题描述】:

我正在尝试在 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>

【问题讨论】:

    标签: vue.js vuetify.js


    【解决方案1】:

    问题在于this.$refs.input 不是底层的HTML 输入元素。要获取输入元素,请执行类似...

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

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

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

    Demo

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2020-08-31
        • 1970-01-01
        • 1970-01-01
        • 2020-08-14
        • 1970-01-01
        • 2013-02-24
        • 2022-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多