2016-10-04 63 views
1

jQuery $(「#element」)。focus();函數在v-if div中第一次不起作用。Vue.js jQuery.focus不起作用

你好,我有Vue js的下一個問題。我有一個div,它隱藏在v-if的負載中。當v-if條件爲真時,將顯示div,但該div內的輸入字段不想進行聚焦。 $( 「#元素」)。對焦();.這隻發生在第一次,div顯示後.focus()的作品

ex。我的方法

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. 
} 

此功能的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> 

一旦this.boxes.lenght盒> 0調用$( 「#UPC」)專注()。正在工作,並將重點放在輸入字段。

回答

4

兩件事情嘗試:

  1. 使用Vue公司的nextTick使聚焦通話發生在接下來的DOM更新(在DOM完全與您的視圖模型變化的結果填充):

    Vue.nextTick(function() { $('#upc').focus(); }); 
    
  2. 嘗試vue-focus它將焦點操作綁定到模型屬性(這意味着您可以擺脫jQuery)。

+0

Ty sir,nextTick就像一個魅力。 –