如何在 vuetify 和打字稿中以编程方式关注 v-textarea?

新手上路,请多包涵

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

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

((this.refs.vtextarea as Vue).$el as HTMLElement).focus()

ETC…

Javascript 源代码对我来说几乎不可读,但不得不这样做很难过……

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

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

原文由 Renetik 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 478
1 个回答

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

这就是我们对 inputtextarea 的一般做法。 We actually use this code with the ref set to our form in order to focus the first visible textarea or input .但是,您可以只定位适合您需要的小部件。

 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)
          }
  });
}

$nextTicksetTimeout 的延迟可以忽略不计,经常需要,并且会一次又一次地为你节省时间。

您也不 需要 排除 type=hidden ,但这不会造成伤害。

If the ref is not an HTMLElement , but instead a VueComponent , you may need to use this.$refs.myRef.$el to get the DOM element.

原文由 Steven Spungin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题