2016-01-22 103 views
5

我試圖在Vue.js中設置輸入元素的焦點。我在網上找到了一些幫助,但沒有任何解釋對我有用。在vue.js中設置輸入元素的焦點

這裏是我的代碼:

<template> 
    <form method="post" action="" v-on:submit.prevent="search"> 
     <input type="text" placeholder="Person name" required v-model="name" v-el="nameInput" /> 
     <input type="text" placeholder="Company" required v-model="company" v-el="domainInput" /> 
     <input type="submit" value="Search" class="btn show-m" /> 
    </form> 
</template> 

<script> 
export default { 
    data() { 
     return { 
      contacts: [], 
      name: null, 
      company: null 
     } 
    }, 
    ready: { 
     // I tried the following : 
     this.$$.nameInput.focus(); 
     this.$els.nameInput.focus(); 
     // None of them worked ! 
    } 
    methods: { 
     search: function (event) { 
      // ... 

      // I also would like to give the focus here, once the form has been submitted. 
      // And here also, this.$$ and this.$els doesn't work 
     }, 
    } 
} 
</script> 

我想什麼,我能在網上找到目標的重點this.$$.nameInput.focus();this.$els.nameInput.focus();,但this.$$是不確定的,而this.$els是空的。

如果能幫忙,我使用vue.js v1.0.15

謝謝您的幫助。

回答

3

有幾個問題。

首先V-EL s的這樣定義:

<input v-el:input-element/> 

那將打開變量在代碼中的駝峯。你可以閱讀更多關於這個奇怪的功能here

除此之外,您應該可以通過this.$els.inputElement訪問該變量。請注意,它只會出現在你定義該元素的組件(或主應用程序本身,如果你在那裏定義它)。

其次,自動對焦似乎並沒有工作在Firefox(43.0.4),至少在我的機器上。一切工作在Chrome上都很棒,並且按預期着重。

+0

這就是奇怪,爲什麼functionning的是這樣的:

Vue.directive('focus', { inserted: function (el) { el.focus() } }) 

然後你就可以在輸入和其他元素使用v-focus屬性? (如果你有任何想法)。 'v-el =「XXX」'更符合邏輯否? –

+0

但是這個工作,所以你應該有我接受的答案:)謝謝 –

+2

[這](https://github.com/vuejs/vue/issues/1292)是當前功能的基本思維過程。 – Andrius

18

在vue 2.x中,您可以用指令解決它。

<input v-focus> 
+0

這個答案應該被標記爲解決方案。它可以在firefox和chrome中正常工作。 – dahrens

+0

它確實有效。但是,我不得不使用 '''插入:{。 EL .__ VUE __對焦() }功能(EL) ''' 也許是因爲我使用VUE元素的UI。 –

相關問題