我昨天才开始使用vue.js
编码,我不知道如何在不使用“传统”JS方式(即document.getElementById('myTextBox').focus()
)的情况下“关注”文本框。Vue:如何调用按钮上的.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 */
有谁知道如何做到这一点?请帮忙。
UPDATE:
添加autofocus
上input
不聚焦在页面加载之后的伎俩。但在我的应用程序中,需要多次重新调整输入字段而不重新加载页面,这就是为什么我需要一种方法来呼叫.focus()
。
更新:一位高级开发人员刚刚帮我解决了这个问题。我发布了下面的代码作为答案,以防别人来这里出现同样的问题。感谢所有的帮助,伙计们。 – ITWitch