admin管理员组文章数量:1294708
I am trying to focus on a textarea in Vue.js, but I am getting the following error:
TypeError: _this2.$refs[ref].focus is not a function
This is the textarea:
<textarea v-model="text[key].content" :ref="text[key].text_id" class="text-textarea" @focus="makeCurrent(key)" v-on:keyup="detectVariable(key, text[key].text_id)"></textarea>
This is my code:
let ref = 'foobar';
console.log(this.$refs[ref]);
this.$refs[ref].focus();
The console.log
prints out the correct textarea:
0: textarea.text-textarea
But when I try to focus I get the error mentioned above. I don't understand this behavior at all. The ref
exists and points to the correct textarea
(it's the only textarea
on the page for now, to avoid confusion) but focus
is not a function on it?
I am trying to focus on a textarea in Vue.js, but I am getting the following error:
TypeError: _this2.$refs[ref].focus is not a function
This is the textarea:
<textarea v-model="text[key].content" :ref="text[key].text_id" class="text-textarea" @focus="makeCurrent(key)" v-on:keyup="detectVariable(key, text[key].text_id)"></textarea>
This is my code:
let ref = 'foobar';
console.log(this.$refs[ref]);
this.$refs[ref].focus();
The console.log
prints out the correct textarea:
0: textarea.text-textarea
But when I try to focus I get the error mentioned above. I don't understand this behavior at all. The ref
exists and points to the correct textarea
(it's the only textarea
on the page for now, to avoid confusion) but focus
is not a function on it?
-
@kiner_shah Defined? I've never needed to explicitly define
$refs
inVue
before. – sveti petar Commented Nov 9, 2021 at 9:21 -
1
Is the text area within a v-for loop? If so, ref behaves differently and is an array of the refs within that loop. For example, if I have a
ref
of 'textArea` with 3 iterations of the loop, I have this.$refs['textArea'][0], this.$refs['textArea'][1], this.$refs['textArea'][2]. To focus the first I'd dothis.$refs['textArea'][0].focus()
– steve16351 Commented Nov 9, 2021 at 9:23 - @steve16351 Yeah that's it. There's a for loop. I was blinded by the fact there's only one element in it so far. – sveti petar Commented Nov 9, 2021 at 9:39
1 Answer
Reset to default 9When a ref
is used inside a v-for
loop, it behaves differently, and the ref is an array of the elements/ponents with a given ref within the loop.
For example, if I have the following, where keys contains multiple values,
<div v-for="key in keys">
<textarea ref="textAreaInput">
</div>
To focus the first, I'd do this.$refs['textAreaInput'][0].focus()
本文标签: javascriptquotfocus is not a functionquot in Vuejs even though element existsStack Overflow
版权声明:本文标题:javascript - "focus is not a function" in Vue.js even though element exists - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741605210a2387936.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论