【问题标题】:Vue.js: How do I focus to an input just unhiddenVue.js:我如何专注于未隐藏的输入
【发布时间】:2020-04-11 23:55:21
【问题描述】:

这一定是非常基本的东西,但我无法理解。

我的<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>

所以,当页面加载时,editable=false 会显示一个文本。当您单击文本时,有一个函数将使editable 为真,因此它会显示输入。这工作正常。现在,我的问题是,一旦editable 变为true,我如何关注input

我读过一些文章:herehere,还有一些文章说我可以通过一些简单的代码来关注元素:

this.$refs.nota.focus()

所以makeEditable 代码是:

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

问题是,我得到这个错误:

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

我很确定这是因为我试图将注意力集中在一个尚未创建的元素上,因为如果我对始终显示的 input 元素进行相同的操作,它就会完美地工作。

那么正确的方法是什么?

【问题讨论】:

  • 如果您在this.editable = true; 之后尝试Vue.nextTick(() =&gt; this.$refs.nota.focus()) 会怎样?它告诉 Vue 等到更改完成。见the doc
  • 你是个天才,立竿见影。非常感谢,您想把它写成答案吗?

标签: javascript vue.js


【解决方案1】:

你可以试试Vue.nextTick(callback)如下:

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

它告诉 Vue 等到更改完成后再调用回调。
请参阅documentation for more

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-10
    • 2014-09-18
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多