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:
<template>
<div>
<!-- Button with a reference -->
<button ref="myButton" @click="focusButton">Click me to focus</button>
</div>
</template>
<script>
export default {
methods: {
focusButton() {
// Call .focus() on the button element using the template reference
this.$refs.myButton.focus();
}
}
};
</script>
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.