Vue.js jQuery.focus 不起作用

Vas*_*sov 1 vue.js

jQuery $("#element").focus(); 函数第一次在 v-if div 中不起作用。

你好,我有 Vue js 的下一个问题。我有一个 div,它在加载时用 v-if 隐藏。当 v-if 条件为真时,显示 div 但该 div 内的输入字段不想聚焦。$("#element").focus();。这仅发生在第一次,在显示 div 之后 .focus() 工作

前任。我在方法中有这个功能

addBox: function (event)
{
    this.boxes.push({id: 1, name: 'Name', weight: 10 }); // Default is empty array. Comes true when i call this function and the div with #upc input becomes active and displayed
    $("#upc").focus(); // When the first time boxes becomes true $("#upc").focus(); does not work. Once is displayed it works after. 
}
Run Code Online (Sandbox Code Playgroud)

html

<div class="row" v-show="boxes.length > 0">
    <div class="col-md-6">
        <input v-model="upc" type="text" class="form-control" name="upc" placeholder="Scan UPC here" id="upc" @keyup.13="scan">
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

一旦 this.boxes.lenght 框 > 0 调用 $("#upc").focus(); 正在工作并将聚焦输入字段。

Pat*_*ele 6

尝试两件事:

  1. 使用 Vue 的nextTick使焦点调用发生在下一次 DOM 更新(一旦 DOM 被视图模型更改的结果完全填充):

    Vue.nextTick(function() { $('#upc').focus(); });
    
    Run Code Online (Sandbox Code Playgroud)
  2. 尝试将焦点操作绑定到模型属性的vue-focus(这意味着您可以摆脱 jQuery)。