5
<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

2

1 Answer 1

8

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>

Sign up to request clarification or add additional context in comments.

2 Comments

This worked make const inputField = ref();
@Beluga B69 hey mate , yes my bad, I corrected the answer, cheers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.