Is it possible to use ref
with el-input
component from Element-UI? I am trying to use $refs
to 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.
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.
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.
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.
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.
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>
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With