vue.js put focus on input

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

HTML


  {{ node.title }}

&         


        
5条回答
  •  长情又很酷
    2021-01-07 23:49

    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!!

提交回复
热议问题