Focus on an input field with a button click VueJS 3
·
Answer a question
<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
Answers
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>
更多推荐

所有评论(0)