Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $refs with Element UI's input component

Tags:

vue.js

vuejs2

Is it possible to use ref with el-input component from Element-UI? I am trying to use $refsto focus on the input when my Vue instance is mounted. Here is my code:

<div id="app">
    <el-input type="text" ref="test" placeholder="enter text"></el-input>
</div>

And in my Vue instance:

new Vue({
  el: "#app",
  mounted(){
    this.$refs.test.focus()
  }
})

The focus method is not working at all, even if I move this.$refs.test.focus() into a method and try to trigger it through an event.

like image 783
Mahmud Adam Avatar asked Dec 06 '16 07:12

Mahmud Adam


People also ask

How to get a ref to the <input> element in react?

Also to get a ref to the <input /> element you should use the inputRef prop. Read about it here. If your React is up to date you should use createRef or the useRef hook. Below are some examples // Using the useRef () hook.

What is the use of ReFS in HTML?

The ref is used to return a reference to the element. Refs should be avoided in most cases, however, they can be useful when we need DOM measurements or to add methods to the components. The following example shows how to use refs to clear the input field.

How to use refs to clear the input field?

The following example shows how to use refs to clear the input field. ClearInput function searches for element with ref = "myInput" value, resets the state, and adds focus to it after the button is clicked. Once the button is clicked, the input will be cleared and focused.

How do I Create A ref in a functional component?

To create a ref in a functional component we use the useRef () hook which returns a mutable object with a .current property set to the initialValue we passed to the hook. This returned object will persist for the full lifetime of the component. Thus, throughout all of its re-rendering and until it unmounts.


2 Answers

The $refs object stores Vue components and should be working fine. The problem is that you are attempting to invoke a focus method which doesn't exist in the component, but rather on an input somewhere inside the component's template.

So, to actually find the input you'd have to do something like this:

this.$refs.test.$el.getElementsByTagName('input')[0].focus();

Not the prettiest line of code ever made, right? So, instead of calling anything in your app's mounted method, if you want to autofocus on the input, just do this:

<el-input type="text" placeholder="enter text" autofocus></el-input>
like image 146
Tomas Buteler Avatar answered Oct 20 '22 00:10

Tomas Buteler


This can be also solved your problem.

// Focus the component, but we have to wait
// so that it will be showing first.
   this.$nextTick(() => {
       this.$refs.inputText.focus();
   });
like image 33
Günay Gültekin Avatar answered Oct 19 '22 23:10

Günay Gültekin