[Vuejs]-Vue Js – focusing on element programatically

0👍

Try this:

this.$refs.email.$el.focus();

0👍

Here is a solution that works, I’ve added a method onSubmit which is called when the form submits and inside it I validate email field, and focus it if is not valid. The key here is nextTick which makes sure to wait before Vue does any DOM update it needs before focusing the element.

<!DOCTYPE html>
<head>
    <title>V3 Example</title>
    <script src="https://unpkg.com/vue@3"></script>        
</head>
<style type="text/css">
    form input, form button {
        display: block;
        margin: 3px;
    }
</style>

<body>
    <div id="app">
        <form @submit.prevent="onSubmit" >
            <h3></h3>
            <input type="username" v-model="username" />
            <input ref="email" type="email" v-model="email" />
            <input type="password" v-model="passwd" autocomplete="off"/>
            <button @click="logIt" >Login </button>
        </form>
    </div>
    <script>
        let app = Vue.createApp({
            data() {
                return {
                    username: '',
                    email: '',
                    passwd: '',
                }
            },

            methods: {
                logIt() {                        
                    console.log('here!');
                                    },
                                    onSubmit() {
                                        if (!this.email.includes('@')) {
                                            this.$nextTick(() => { // must wait for next tick before interacting with DOM
                                                this.$refs.email.focus();
                                                console.log('Not valid email!');
                                            })
                                        }
                                    }
            },

            watch: {

                email(val1, val2){
                    if (!val2.includes('@')) {
                        this.$refs.email.focus(); // <- this is supposed to return focus to email input
                        console.log('Not valid email!');
                    }
                    else {
                        console.log(val1);
                        console.log(val2);                            
                    }
                }

            }
        })

        app.mount('#app');
    </script>
</body>

Leave a comment