Home > database >  Focus on an input field with a button click VueJS 3
Focus on an input field with a button click VueJS 3

Time:06-19

<template>
  <button @click="focusInput">Click me to focus on the input</button>
  <input ref="inputField" type="text">
</template>

<script setup>
  const focusInput = () => {
    this.$refs.inputField.focus();
  };
</script>

I'm trying to set the focus into the input field on a button click but does not work with Vue 3. Really appreciate it if somebody can help. Thanks

CodePudding user response:

Try like following snippet (this is something else in script setup, and you can not use $refs):

<script setup>
  import { ref } from 'vue'
  const inputField = ref()
  const focusInput = () => {
    inputField.value.focus();
  };
</script>

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const inputField = ref()
    const focusInput = () => {
      inputField.value.focus()
    }
    return { focusInput, inputField }
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <button @click="focusInput">Click me to focus on the input</button>
    <input ref="inputField" type="text">
</div>

  • Related