温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - vue.js put focus on input
html javascript vue.js

javascript - vue.js专注于输入

发布于 2020-03-27 11:28:42

的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()
    }
},

我是日本初学者Web开发人员。我英语不好,对不起。

HTML位于“ v-for”(v-for="node in list")中。

双击文本时,它变为<input>

我想使其在出现时专注于输入。

我试过了,但是没有用。

的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())
},

控制台上没有错误,但是没有用。

查看更多

查看更多

提问者
Kuru
被浏览
159
Phil 2018-08-30 12:39

您的主要问题是$nextTick需要回调函数,但是您正在执行

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

立即。您可以使您的代码正常工作

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

但是,我认为您会遇到进一步的问题,并且可以使您的代码更简单。

您会发现一个问题是,由于您的样式规则,双击其中的任何一个节点输入都会变得可见。

您可以改为将“编辑”标志存储node或单独对象中的某个位置。

下面是一个通过...简化代码的示例。

  1. 使用在循环中ref使用时的类似数组的性质v-for,以及
  2. enter@keydown事件绑定使用修饰符

new Vue({
  el: '#app',
  data: {
    list: [
      {id: 1, title: 'Node #1'},
      {id: 2, title: 'Node #2'}
    ],
    editing: {}
  },
  methods: {
    showInput(id, index) {
      this.$set(this.editing, id, true)
      
      this.$nextTick(() => {
        this.$refs.input[index].focus()
      })
    },
    hideInput(id) {
      this.editing[id] = false
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<ul id="app">
  <li v-for="(node, index) in list">
    <span v-show="!editing[node.id]" @dblclick="showInput(node.id, index)">
      {{ node.title }}
    </span>
    <input v-show="editing[node.id]" type="text"
           ref="input" :value="node.title"
           @blur="hideInput(node.id)" @keydown.enter="hideInput(node.id)">
  </li>
</ul>