通过单击按钮聚焦输入字段 VueJS 3

Mis*_*ana 5 javascript vue.js vue-component vuejs3

<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>
Run Code Online (Sandbox Code Playgroud)

我试图在单击按钮时将焦点设置到输入字段中,但不适用于 Vue 3。如果有人可以提供帮助,我将不胜感激。谢谢

Nik*_*vic 7

尝试像下面的代码片段(this是脚本设置中的其他内容,您不能使用$refs):

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

<script setup>
  import { ref } from 'vue'
  const inputField = ref()
  const focusInput = () => {
    inputField.value.focus();
  };
</script>
Run Code Online (Sandbox Code Playgroud)
const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const inputField = ref()
    const focusInput = () => {
      inputField.value.focus()
    }
    return { focusInput, inputField }
  },
})
app.mount('#demo')
Run Code Online (Sandbox Code Playgroud)