30

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

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

When span element is double-clicked, it gets hidden and the <input> element is shown.

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.

4
  • Thank you so much for a comment. You mean like this? this.$nextTick(this.$refs["input_" + id].focus())
    – Kuru
    Commented Aug 30, 2018 at 3:10
  • Uncaught TypeError: this.$refs[("input_" + t)].focus is not a function at VueComponent.showInput (sl-vue-tree.js?c536:8) at dblclick (sl-vue-tree.js?c536:8) at invoker (vue.runtime.esm.js?2b0e:2023) at HTMLSpanElement.fn._withTask.fn._withTask (vue.runtime.esm.js?2b0e:1822)
    – Kuru
    Commented Aug 30, 2018 at 3:17
  • I got this error(T_T)
    – Kuru
    Commented Aug 30, 2018 at 3:18
  • Sorry, I was incorrect about removing the [0]. For some reason, the $refs property is an array
    – Phil
    Commented Aug 30, 2018 at 4:29

5 Answers 5

36

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
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></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>

2
  • Oh my gosh!!! Thank you so much!!! You are a genius. I haven't used this.$set before. Very technical!
    – Kuru
    Commented Aug 30, 2018 at 5:05
  • @nichika You're most welcome. this.$set is the same as Vue.set. You need to use it for reactivity as initially, editing has no properties so Vue doesn't detect new ones naturally. See vuejs.org/v2/guide/reactivity.html
    – Phil
    Commented Aug 30, 2018 at 5:10
6

The autofocus attribute is your friend:

<input type="text" autofocus />
2
  • (note: autofocus doesn’t work on mobile Safari) from Vue documentation. Commented May 21, 2020 at 7:41
  • 3
    alas, it's more fragile when SPA routing is in play, and only triggers the first time. (it fails to set the focus if you vue-route to another page and eventually back to here.) ref=... and .focus() is passing tests, though I haven't tested this on iOS yet.
    – xander
    Commented Aug 7, 2020 at 3:17
4

The way you use this.$nextTick(); is incorrect. You should pass it a callback function.

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

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


I'm not however sure how that array access is working for you, because as I notice, $refs is an object with the keys referring to the ref name.

[Edit: Thanks to @Phil's comment, above is clear.]


The above is the correct solution for your problem. Since you have already got that answer, I'll add something other than that.

The reason why you see this behavior is that because the reference you hold in $refs doesn't get updated when you change the visibility of the text box in your showInput() method. So when you call this.$refs["input_" + id].focus();, it's actually trying to set focus on a hidden element (because the current reference is not updated).

That's why you need to call the $nextTick() to update it. But if you wanted a quick fix to your problem, without calling $nextTick(), you could update it manually like this:

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

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

This would also work :) Hope it helps!!

5
  • See the note here ~ "When used on elements/components with v-for, the registered reference will be an Array containing DOM nodes or component instances."
    – Phil
    Commented Aug 30, 2018 at 6:03
  • Yeah, that one threw me a little too :)
    – Phil
    Commented Aug 30, 2018 at 6:12
  • Oh!!!! Thank you so much!!! Put focus after displaying it! I see. You are smart!!!
    – Kuru
    Commented Aug 30, 2018 at 6:30
  • @Phil Yes, I noticed the array now. It seems if you aren't using v-for it keeps the refs in an object. However, I'm afraid that your comment about this doesn't seem to be valid. It works perfectly here. jsfiddle.net/un65e9oc/7 Commented Aug 30, 2018 at 6:36
  • 1
    Ah, of course. Vue defaults the $nextTick context param to the current Vue instance.
    – Phil
    Commented Aug 30, 2018 at 6:40
3

if you want to set focus after click on something and show input text box with set focus with vue js

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

and use custom directive for it. In case you need it should work on click then set with click

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

and use it

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

enter code here
0
0

It's work for me when we validate the form and want to set dynamically focus on each field

           this.$validator.validateAll("FORM_NAME").then(valid => {

                var errors = this.$validator.errors;

                if (valid) {
                    console.log('All Fields are valid')
                } else {
                    const errorFieldName = this.$validator.errors.items[0].field;
                    console.log(errorFieldName);
                    this.$refs[errorFieldName].focus();
                }

            });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.