如何在 vuetify 和 typescript 中以编程方式聚焦 v-textarea?

Ren*_*tik 4 javascript typescript vue.js vuetify.js

现在似乎不可能,我尝试了一些疯狂的东西,例如:

(this.refs.vtextarea as any).textarea.focus()

((this.refs.vtextarea as Vue).$el as HTMLElement).focus()
Run Code Online (Sandbox Code Playgroud)

等等...

JavaScript源对我来说是很难读,但是它是可悲的不得不做这样的...

这是一些基本的东西,还是我错过了一些明显的东西?

PS:好吧,我在层次结构中的某个地方看到了 textarea 元素……也许我可以通过一些基本的 dom 子元素访问方式来访问……但这就像编写我一生中最糟糕的代码。

Ste*_*gin 7

Vuetify 在聚焦输入时并不总是有效,即使使用$nextTick.

这就是我们对input和 的一般做法textarea。我们实际上将此代码与refset to our 一起使用form,以便聚焦第一个可见的textareainput。但是,您可以只定位适合您需求的小部件。

mounted() {
  this.$nextTick(() => {
          const theElement = this.$refs.myRef         
          const input = theElement.querySelector('input:not([type=hidden]),textarea:not([type=hidden])')
          if (input) {
            setTimeout(() => {
              input.focus()
            }, 0)
          }
  });
}
Run Code Online (Sandbox Code Playgroud)

延迟的$nextTicksetTimeout可以忽略不计,通常需要,还要再节省您的时间和时间。

你也不需要排除type=hidden,但它不会伤害。

如果ref不是 anHTMLElement而是 a VueComponent,则可能需要使用this.$refs.myRef.$el来获取 DOM 元素。


小智 7

您可以使用自动对焦属性

<v-text-field
                        autofocus
                        label="Insert Document Number*"
                        single-line
                      ></v-text-field>
Run Code Online (Sandbox Code Playgroud)


Dok*_*CRO 5

我让我的工作:

mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.$refs.descriptionDescription.$refs.input.focus()
      })
    })
  },
Run Code Online (Sandbox Code Playgroud)

来自@Thomas 和@Steven Spungin 的代码组合


Tho*_*mas 3

<template>
   <v-text-area
      ref="myTextArea"
   />
</template>

<script>
   ...
   created () {
      this.$refs["myTextArea"].$refs.textarea.focus()
   }
</script>
Run Code Online (Sandbox Code Playgroud)

我对文本字段是这样做的。我认为它应该以同样的方式工作。

  • 对我来说 `this.$refs["myTextArea"].$refs.input.focus();` 有效。 (6认同)