如何在 vuetify 和 typescript 中以编程方式聚焦 v-textarea? [英] How to focus v-textarea programatically in vuetify and typescript?
问题描述
现在似乎不可能,我尝试了一些疯狂的东西,例如:
Seems like impossible now, I tried some crazy stuff like:
(this.refs.vtextarea as any).textarea.focus()
((this.refs.vtextarea as Vue).$el as HTMLElement).focus()
等等...
的Javascript源对我来说是很难读,但是它是可悲的不得不做这样的...
Javascript source is hardly readable for me but it's sad to had to do it like this...
这是一些基本的东西,还是我遗漏了一些明显的东西?
Int this some basic stuff, or am I missing something obvious ?
PS:好吧,我在层次结构中的某处看到了 textarea 元素……也许我可以通过一些基本的 dom 子元素访问方式来访问……但这就像编写我一生中最糟糕的代码.
PS: well I see textarea element somewhere there in hierarchy... Maybe I can access by some basic dom child element access way... but this will be like writing worst code of my life.
推荐答案
Vuetify 在聚焦输入时并不总是有效,即使使用 $nextTick
.
Vuetify does not always work when focusing input, even with $nextTick
.
这就是我们对 input
和 textarea
的一般做法.我们实际上使用此代码将 ref
设置为我们的 form
以聚焦第一个可见的 textarea
或 input
.但是,您可以只定位适合您需求的小部件.
This is how we do it generically for both input
and textarea
. We actually use this code with the ref
set to our form
in order to focus the first visible textarea
or input
. However, you can target just the widget that suits your needs.
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)
}
});
}
$nextTick
和 setTimeout
的延迟可以忽略不计,通常是必需的,并且会一次又一次地为您节省时间.
The delay for $nextTick
and setTimeout
is negligible, often required, and will save you time and time again.
您也不需要排除type=hidden
,但这不会造成伤害.
You don't need to exclude type=hidden
either, but it can't hurt.
如果ref
不是HTMLElement
,而是VueComponent
,您可能需要使用this.$refs.myRef.$el
获取 DOM 元素.
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.
这篇关于如何在 vuetify 和 typescript 中以编程方式聚焦 v-textarea?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!