gpt4 book ai didi

javascript - 单击按钮时 Vue : How to call . focus()

转载 作者:数据小太阳 更新时间:2023-10-29 04:30:46 26 4
gpt4 key购买 nike

我昨天才开始使用 vue.js 编码,我不知道如何在不使用“传统”JS 方式(即 document)的情况下“关注”文本框。 getElementById('myTextBox').focus().

最初,我的文本框是隐藏的。我有一个“开始”按钮,当用户点击它时,会显示文本框,我想在那里设置 focus,可以这么说。我已经尝试使用 ref,但无济于事(请参阅下面的代码)。

HTML:

<input id="typeBox" ref="typeBox" placeholder="Type here..." />

Javascript

export default {
name: 'game',

methods: {
startTimer () {
setTimeout(function () { /* .focus() won't work without this */

/* ugly and not recommended */
// document.getElementById('typeBox').focus()

/* Throws the error: Cannot read property 'typeBox' of undefined */
this.$refs.typeBox.focus()

// ... any other options?
// ...

}, 1)
}
} /* END methods */

} /* END export default */

有人知道怎么做吗?请帮忙。

更新:

input 上添加 autofocus 可以在页面加载后立即进行对焦。但是在我的应用程序中,需要在不重新加载页面的情况下多次“重新聚焦”输入字段,这就是为什么我需要一种方法来调用 .focus()

最佳答案

在这里分享解决方案,以防有人遇到同样的问题......

在高级程序员的帮助下,我终于弄明白了这一点。我还能够使用它的 vue 版本 nextTick() 一路消除 setTimeout

正确的JS代码:

startTimer () {
this.$nextTick(() => {

// this won't work because `this.$refs.typeBox` returns an array
// this.$refs.typeBox.focus()

//this one works perfectly
this.$refs.typeBox[0].focus()

})
} /* END startTimer */

解释:

当我使用 console.log(this.$refs.typeBox) 时,它返回了这个数组:

enter image description here

这就是为什么要使代码正常工作,它必须是 typeBox[0].focus() 而不是 typeBox.focus()

关于javascript - 单击按钮时 Vue : How to call . focus(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42695728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com