【发布时间】:2017-07-30 11:03:41
【问题描述】:
我昨天才开始使用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() 的方法。
【问题讨论】:
-
更新:一位高级开发人员刚刚帮助我解决了这个问题。我将下面的代码发布为答案,以防其他人来这里解决同样的问题。感谢所有的帮助,伙计们。
标签: javascript vue.js vuejs2 setfocus