{..."> {..."/> {..."> {...">

vue.js专注于输入

JavaScript Vue.js

路易卡卡西

2020-03-19

的HTML

<span :style="{ display : displayTitle }" @dblclick="showInput()">
  {{ node.title }}
</span>
<input :style="{ display : displayTitleInput }" type="text" 
       @blur="hideInput1" @keydown="hideInput2" 
       @input="changeTitle(node.id , $event.target.value)" 
       :value="node.title">

JS

data() {
  return {
      displayTitle: "inline-block",
      displayTitleInput: "none"
    };
},
showInput() {
    this.displayTitle = "none"
    this.displayTitleInput = "inline-block"
},
hideInput1() {
   this.displayTitle = "inline-block"
   this.displayTitleInput = "none"
},
hideInput2(event) {
    if (event.keyCode === 13) {
        this.hideInput1()
    }
},

I am a beginner Japanese web developer. I am not good at English, sorry.

HTML is in "v-for" (v-for="node in list").

When double click text, it turns to <input>.

I want to make it possible to focus on input when it appears.

I tried this but it didn't work.

HTML

<span :style="{ display : displayTitle }" @dblclick="showInput(node.id)">
  {{ node.title }}
</span>
<input :ref='"input_" + node.id' :style="{display:displayTitleInput}" type="text" 
       @blur="hideInput1" @keydown="hideInput2" 
       @input="changeTitle(node.id , $event.target.value)" 
       :value="node.title">

JS

showInput(id) {
    this.displayTitle = "none"
    this.displayTitleInput = "inline-block"

    this.$nextTick(this.$refs["input_" + id][0].focus())
},

There was no error on console, but didn't work.

第2255篇《vue.js专注于输入》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
Gil十三 2020.03.19

如果您想在单击某物后设置焦点并使用vue js显示设置了焦点的输入文本框

directives: {
  focus: {
    // directive definition
    inserted: function (el) {
      el.focus()
    }
  }
}

并使用自定义指令。如果您需要它,则应在单击时起作用,然后单击设置

directives: {
  click: {
    // directive definition
    inserted: function (el) {
      el.focus()
    }
  }
}

并使用它

<input v-focus> or <input v-click>

enter code here
Itachi小宇宙 2020.03.19

autofocus属性是您的朋友:

<input type="text" autofocus />
Eva神乐 2020.03.19

您使用的方式this.$nextTick();不正确。您应该向它传递一个回调函数。

this.$nextTick(function () {
    this.$refs["input_" + id].focus()
})

https://jsfiddle.net/un65e9oc/7/


但是我不确定该数组访问如何为您工作,因为我注意到,这$refs是一个带有引用引用名称的键的对象。

[编辑:感谢@Phil的评论,上面很清楚。]


以上是解决您问题的正确方法。由于您已经有了答案,因此我将添加其他内容。

之所以会出现这种现象,是因为$refs更改showInput()方法中文本框的可见性时,所保存的引用没有更新因此,当您调用时this.$refs["input_" + id].focus();,它实际上是在尝试设置focus隐藏元素(因为当前引用未更新)。

因此,您需要调用$nextTick()进行更新。但是,如果您想快速解决问题,而无需致电$nextTick(),可以像这样手动更新它:

this.displayTitleInput = "inline-block"
this.$refs["input_" + id].style.display = this.displayTitleInput

this.$refs["input_" + id].focus();

这也将起作用:)希望能有所帮助!

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android