Search code examples
javascriptvue.js

Setting focus of an input element in vue.js


I'm trying to set the focus of an input element in Vue.js. I found some help online but none of the explanation worked for me.

Here's my code :

<template>
    <form method="post" action="" v-on:submit.prevent="search">
        <input type="text" placeholder="Person name" required v-model="name" v-el="nameInput" />
        <input type="text" placeholder="Company" required v-model="company" v-el="domainInput" />
        <input type="submit" value="Search" class="btn show-m" />
    </form>
</template>

<script>
export default {
    data () {
        return {
            contacts: [],
            name: null,
            company: null
        }
    },
    ready: {
        // I tried the following :
        this.$$.nameInput.focus();
        this.$els.nameInput.focus();
        // None of them worked !
    }
    methods: {
        search: function (event) {
            // ...

            // I also would like to give the focus here, once the form has been submitted.
            // And here also, this.$$ and this.$els doesn't work
        },
    }
}
</script>

I tried this.$$.nameInput.focus(); and this.$els.nameInput.focus(); for what I could find online to target the focus, but this.$$ is undefined, and this.$els is empty.

I'm using Vue.js v1.0.15


Solution

  • In vue 2.x you can solve it with a directive.

    Vue.directive('focus', {
        inserted: function (el) {
            el.focus()
        }
    })
    

    Then you can use v-focus attribute on inputs and other elements:

    <input v-focus>