将$ refs与Element UI的输入组件一起使用

Mah*_*dam 7 vue.js vuejs2

是否有可能使用refel-input组件从元素的UI?我试图$refs在安装我的Vue实例时专注于输入.这是我的代码:

<div id="app">
    <el-input type="text" ref="test" placeholder="enter text"></el-input>
</div>
Run Code Online (Sandbox Code Playgroud)

在我的Vue实例中:

new Vue({
  el: "#app",
  mounted(){
    this.$refs.test.focus()
  }
})
Run Code Online (Sandbox Code Playgroud)

focus方法根本不起作用,即使我this.$refs.test.focus()进入一个方法并试图通过一个事件触发它.

Tom*_*ler 11

$refs对象存储Vue组件,应该可以正常工作.问题是您正在尝试调用组件中不存在focus方法,而是调用组件模板内某处的输入.

所以,要真正找到输入,你必须做这样的事情:

this.$refs.test.$el.getElementsByTagName('input')[0].focus();
Run Code Online (Sandbox Code Playgroud)

不是有史以来最漂亮的代码,对吗?因此,mounted如果您想在输入中自动对焦,而不是在应用程序的方法中调用任何内容,只需执行以下操作:

<el-input type="text" placeholder="enter text" autofocus></el-input>
Run Code Online (Sandbox Code Playgroud)