Vue Answers

How to call .focus() on button click with Vue.js?

Spread the love

To call the .focus() method on a button click in Vue.js, you can use a combination of template references (ref) and Vue’s event handling. Here’s how you can do it:

    <!-- Button with a reference -->
    <button ref="myButton" @click="focusButton">Click me to focus</button>

export default {
  methods: {
    focusButton() {
      // Call .focus() on the button element using the template reference

In this example, the button has a ref attribute (ref="myButton"), which allows us to reference the button element in the component’s JavaScript code.

When the button is clicked (@click="focusButton"), the focusButton method is called.

Inside the focusButton method, we access the button element using this.$refs.myButton and call the .focus() method on it to give it focus.

This way, when the button is clicked, it will receive focus programmatically.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *