How to set focus() to input?

I would like to set focus() to input when click btn

<template>
    <div>
        <el-form :model="form" ref="form">
            <el-input v-model="form.email">
            </el-input>

            <el-button type="primary" @click="setFocus">
            </el-button>
        </el-form>
    </div>
</template>

<script>
    export default {
        name: 'Login',
        data() {
            return {
                form: {
                    email: '',
                },
            };
        },
        methods: {
            setFocus() {
                 this.form.email.focus()// don't  work
            },
        }
    }
</script>
<el-input ref="email" v-model="form.email">
this.$refs.email.$el.focus()
10 Likes

Thanks, Could you explain?

ref isl a attribute of vue. It is used to register a reference to any html elememt or child component.

It is just like setting an id to an element so that you can reference it in javascriptThe reference will be registered under the parent component’s $refs object

So in your code you can refer an element by using

this.$refs.yourElementRefAttributeValue

This returns the html elememt object that you have set the ref attribute on. So ypu can use all the methods of the html object

For further info https://vuejs.org/v2/api/#ref

1 Like

I tried, but don’t work

jsFiddle

It work fine, when I tried this.$refs.input.$el.children[0].focus();.
I don’t understand???

Well, I guess the input is not the root element of that el-input component (probably wrapped in a <div>), so you have to get it from the children of the root element.

I don’t know the structure of your component, so I can’t be much more specific.

Note: Sometimes you need to call focus in the next tick

this.$nextTick(() => this.$refs.input.focus())
24 Likes

Any Idea why? This just solved my problem

Probably because you are waiting for the component to fully mount in the browser. Just a guess.

1 Like

Maybe should add to your comment:

Normal input elements don’t require the .$el addition.
this.$refs.email.focus()

4 Likes

use this code : this.$refs.input.$refs.input.focus()

And for the .Typescript users:

let theField = <HTMLInputElement>this.$refs.input;
    theField.focus();

It simply because the element you have to use for reference is component not an input field. You need to console.log the this.$refs.input.$el and find out the text input within the component then use focus() function. That’s the reason why .children[0] is necessary.

Yes! Thanks, this fixed this problem for me :grinning:

thanks, solved for me!

I got Parsing error: JSX element ‘HTMLInputElement’ has no corresponding closing tag.

solved with:

$refs!: {
userId: HTMLInputElement;
};

this.$refs.userId.focus();

You can use the autofocus attribute, eg

<input type="text" autofocus />

6 Likes

Nice!!! Thanks…

Nice!! before I did not expect to complete the components are not mounted