2017-03-09 3202 views
3

我昨天才开始使用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:

添加autofocusinput不聚焦在页面加载之后的伎俩。但在我的应用程序中,需要多次重新调整输入字段而不重新加载页面,这就是为什么我需要一种方法来呼叫.focus()

+0

更新:一位高级开发人员刚刚帮我解决了这个问题。我发布了下面的代码作为答案,以防别人来这里出现同样的问题。感谢所有的帮助,伙计们。 – ITWitch

回答

7

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

我终于在高级程序员的帮助下计算出了这一点。我还能够使用其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()

+1

可以证实我只是不得不为我的工作使用这个非常好的解决方案。使用$ nextTick是这种方式,并忘记使用setTimeout – munkee

+0

您的数组可能是由v-for引起的吗? “在使用v-for的元素/组件上使用时,注册的引用将是包含DOM节点或组件实例的数组。” – mix3d

3

thissetTimeout函数的值将被设定为window对象,因为它是在一段时间之后执行回调函数并将其已经失去了其动态地从函数被调用,其中设置this关键字的范围。

箭头函数不绑定它自己的值this

startTimer() { 
    setTimeout(() => { 
    this.$refs.typeBox.focus() 
    }, 1) 
} 

OR

startTimer() { 
    const self = this; 
    setTimeout(function() { 
    self.$refs.typeBox.focus() 
    }, 1) 
} 
+0

谢谢,但它仍然无法正常工作。该错误现在已更改为'_this。$ refs.typeBox.focus不是函数'。我试着从'focus()'中移除'()',它没有抛出错误,但仍然不会集中。第二个选项也会抛出上面提到的原始错误。 – ITWitch

+0

现在检查,只是更新了我的答案。 @ITWitch –

+0

谢谢,但是从'$ refs'中删除美元符号也无济于事。 – ITWitch

-1

看到这一点:

$(function(){ 
 
    $("#my_text").hide(); 
 
}) 
 

 
function onClickTest(){ 
 
    $("#my_text").show(); 
 
    document.getElementById("my_text").focus(); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="my_text"/> 
 

 
    <button onclick="onClickTest()">click</button>

+0

此问题未使用jQuery标记,设置焦点根本不需要jQuery。 – str

+0

@str我没有使用jQuery的焦点,只是使用元素来隐藏/显示测试字段 –

+0

谢谢,但正如我上面提到的,我不应该使用'document.getElementById',因为它以某种方式击败首先使用'vue.js'的目的。 – ITWitch