<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.如果有人能帮忙,我真的很感激.谢谢

推荐答案

try 以下代码段(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>

Javascript相关问答推荐

事件错误:类型错误:无法读取未定义的属性(读取stopPropagation)

在具有焦点和上下文的d3多线图表中,如何将上下文的刷新限制在特定日期?

vanillajs-datepicker未设置输入值,日期单击时未触发更改事件

使用AJX发送表单后,$_Post看起来为空

vscode扩展-webView Panel按钮不起任何作用

Javascript,部分重排序数组

为什么!逗号和空格不会作为输出返回,如果它在参数上?

处理时间和字符串时MySQL表中显示的日期无效

如何将react—flanet map添加到remixjs应用程序

连接到游戏的玩家不会在浏览器在线游戏中呈现

在开发期间,Web浏览器如何运行&qot;.jsx&qot;文件?

如何使用基于promise (非事件emits 器)的方法来传输数据?

第一项杀死下一项,直到数组长度在javascript中等于1

图表4-堆叠线和条形图之间的填充区域

更改agGRID/Reaction中的单元格格式

我怎样才能得到一个数组的名字在另一个数组?

ReferenceError:无法在初始化之前访问setData

FindByIdAndUpdate在嵌套对象中创建_id

如何使用puppeteer操作所有选项

使用VITE开发服务器处理错误