2016-01-22 102 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。 –

相关问题