简体   繁体   English

Vue.js:我如何专注于刚刚未隐藏的输入

[英]Vue.js: How do I focus to an input just unhidden

This must be something really basic, but I can't get it.这一定是非常基本的东西,但我无法理解。

I have this piece of code in my <template> :我的<template>中有这段代码:

<div v-if="this.editable">
    <input type="text" ref="nota" :id="notaid" v-model="nombre" v-on:keyup.enter="enviar" v-on:blur="enviar" class="form-control">
</div>
<div v-else>
    <p @click="makeEditable">{{ nombre }}</p>
</div>

So, when the page loads, editable=false so it displays a text.因此,当页面加载时, editable=false会显示一个文本。 When you click in the text there's a function that will make editable true, so it displays the input.当您单击文本时,有一个 function 将使editable为真,因此它显示输入。 This works fine.这工作正常。 Now, my problem is, how do I focus on the input as soon as editable changes to true?现在,我的问题是,一旦editable更改为 true,我如何专注于input

I have read some articles: here , here , and some others that says I could be focusing on the element with some code as simple as:我已经阅读了一些文章: herehere和其他一些文章,这些文章说我可以使用一些简单的代码来关注元素:

this.$refs.nota.focus()

So makeEditable code is:所以makeEditable代码是:

methods: {
  makeEditable() {
    this.editable = true;
    this.$refs.nota.focus()
  },
  ...

Problem is, I get this error:问题是,我收到此错误:

app.js:38487 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'focus' of undefined"

I'm pretty sure this is because I'm trying to focus to an element that hasn't been created yet, because if I make the same on an input element that is always displayed, it works perfectly.我很确定这是因为我试图将注意力集中在一个尚未创建的元素上,因为如果我在始终显示的input元素上做同样的事情,它就会完美地工作。

So which is the right way?那么哪种方法是正确的呢?

You can try Vue.nextTick(callback) as follow:您可以尝试Vue.nextTick(callback)如下:

methods: {
  makeEditable() {
    this.editable = true;
    Vue.nextTick(() => 
      this.$refs.nota.focus()
    )
  },
  ...

It tells Vue to wait until the changes are made and then call the callback.它告诉 Vue 等到更改完成后再调用回调。
See the documentation for more .有关更多信息,请参阅文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM