即使元素存在,Vue.js 中的“焦点不是函数”

jov*_*van 3 javascript vue.js

我试图专注于 Vue.js 中的文本区域,但出现以下错误:

TypeError: _this2.$refs[ref].focus is not a function
Run Code Online (Sandbox Code Playgroud)

这是文本区域:

<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>
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

let ref = 'foobar';
console.log(this.$refs[ref]);
this.$refs[ref].focus();
Run Code Online (Sandbox Code Playgroud)

打印console.log出正确的文本区域:

0: textarea.text-textarea
Run Code Online (Sandbox Code Playgroud)

但是当我尝试集中注意力时,我收到了上面提到的错误。我完全不理解这种行为。存在ref并指向正确的(这是目前页面上textarea唯一的,以避免混淆),但不是它的函数?textareafocus

ste*_*351 8

当 aref在循环内部使用时v-for,它的行为有所不同,并且 ref 是循环内具有给定 ref 的元素/组件的数组。

例如,如果我有以下内容,其中键包含多个值,

<div v-for="key in keys">
    <textarea ref="textAreaInput">
</div>
Run Code Online (Sandbox Code Playgroud)

为了专注于第一个,我会做this.$refs['textAreaInput'][0].focus()