vue.js put focus on input

前端 未结 5 1190
野趣味
野趣味 2021-01-07 22:58

HTML


  {{ node.title }}

&         


        
5条回答
  •  一整个雨季
    2021-01-07 23:51

    Your primary problem is that $nextTick takes a callback function but you are executing

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

    immediately. You could get your code working correctly with

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

    However, I think you'll run in to further problems and your code can be made much simpler.

    One problem you'll find is that all your node inputs will become visible when double-clicking on any of them due to your style rules.

    You could instead store an "editing" flag somewhere either on the node or in a separate object.

    Below is an example that simplifies your code by...

    1. Using the array-like nature of ref when used within a v-for loop, and
    2. Using the enter modifier on your @keydown event binding

    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
        }
      }
    })
    
    
    • {{ node.title }}

提交回复
热议问题