【问题标题】:Focus on an input field with a button click VueJS 3使用按钮单击 VueJS 3 专注于输入字段
【发布时间】:2022-11-14 12:26:54
【问题描述】:
<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>

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

【问题讨论】:

标签: javascript vue.js vue-component vuejs3


【解决方案1】:

尝试如下 sn-p (this 是脚本设置中的其他内容,您不能使用$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>

【讨论】:

  • 这有效 make const inputField = ref();
  • @Beluga B69 嘿,伙计,是的,我的错,我更正了答案,干杯:)
猜你喜欢
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多