Javascript 如何在vuetify和typescript中以编程方式聚焦v-textarea?
现在似乎不可能了,我尝试了一些疯狂的东西,比如:Javascript 如何在vuetify和typescript中以编程方式聚焦v-textarea?,javascript,typescript,vue.js,vuetify.js,Javascript,Typescript,Vue.js,Vuetify.js,现在似乎不可能了,我尝试了一些疯狂的东西,比如: (this.refs.vtextarea as any).textarea.focus() ((this.refs.vtextarea as Vue).$el as HTMLElement).focus() 等等 Javascript源代码对我来说几乎不可读,但不得不这样做很遗憾 这是一些基本的东西,还是我遗漏了一些明显的东西 PS:我在层次结构中的某个地方看到textarea元素。。。也许我可以通过一些基本的dom子元素访问方式。。。但这就
(this.refs.vtextarea as any).textarea.focus()
((this.refs.vtextarea as Vue).$el as HTMLElement).focus()
等等
Javascript源代码对我来说几乎不可读,但不得不这样做很遗憾
这是一些基本的东西,还是我遗漏了一些明显的东西
PS:我在层次结构中的某个地方看到textarea元素。。。也许我可以通过一些基本的dom子元素访问方式。。。但这就像是在写我一生中最糟糕的代码。
<template>
<v-text-area
ref="myTextArea"
/>
</template>
<script>
...
created () {
this.$refs["myTextArea"].$refs.textarea.focus()
}
</script>
...
创建(){
这是.$refs[“myTextArea”]。$refs.textarea.focus()
}
我这样做是为了文本字段。我认为它应该以同样的方式工作。在新答案中编辑:
尝试在引用后添加$el。像这样:
this.$nextTick(()=>this.$refs.cancelTestDialog.$el.focus())
还要确保将“ref”定义为组件上的属性
Vue ref通过在组件上添加一个ref=“
属性来工作,您可以使用此属性进行选择。$refs
OLD:在绘制textarea之前,需要等待一个勾号。你可以
使用setTimeout之类的技巧或使用此Vue函数:
this.$nextTick(()=>{
此。$refs..focus()
})
Nexttick的功能基本上与setTimeout相同
目前我的解决方案是:
(this.$refs.<name>.$el.childNodes[0].childNodes[0].childNodes[0].childNodes[0] as HTMLElement).focus()
(this.$refs..$el.childNodes[0]。childNodes[0]。childNodes[0]。childNodes[0]作为HTMLElement)。焦点()
但正如我在尝试这种方法之前所说的,它尽可能的丑陋。但是有效。Vuetify在聚焦输入时并不总是有效,即使使用
$nextTick
对于输入
和文本区域
,我们通常都是这样做的。实际上,我们将此代码与ref
设置为表单
一起使用,以便聚焦第一个可见的文本区域
或输入
。但是,您可以只针对适合您需要的小部件
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
的延迟可以忽略不计,通常是必需的,并且可以一次又一次地为您节省时间
您也不需要排除type=hidden
,但这不会造成伤害
如果ref
不是HTMLElement
,而是VueComponent
,您可能需要使用this.$refs.myRef.$el
来获取DOM元素。适合我
setTimeout(() => {
this.$refs.textNote.$refs.input.focus()
})
我让我的工作与此:
mounted() {
this.$nextTick(() => {
setTimeout(() => {
this.$refs.descriptionDescription.$refs.input.focus()
})
})
},
来自@Thomas和@Steven Spungin的代码组合这是纯JavaScript,不是TypeScript,但对我来说很有用:
<v-textarea ref="entry"></v-textarea>
<script>
export default {
mounted() {
this.$refs["entry"].focus();
}
}
</script>
导出默认值{
安装的(){
此.$refs[“条目”].focus();
}
}
我的v-text-field使用了以下功能:
您可以使用“自动聚焦”属性
<v-text-field
autofocus
label="Insert Document Number*"
single-line
></v-text-field>
遗憾的是,这里没有下一个勾号,当它已经呈现并准备就绪时,我会调用它。$refs[“myTextArea”]。$refs.input.focus()代码>工作。
<v-text-field
autofocus
label="Insert Document Number*"
single-line
></v-text-field>