简体   繁体   English

在 vue.js 中设置输入元素的焦点

[英]Setting focus of an input element in vue.js

I'm trying to set the focus of an input element in Vue.js.我正在尝试在 Vue.js 中设置输入元素的焦点。 I found some help online but none of the explanation worked for me.我在网上找到了一些帮助,但没有一个解释对我有用。

Here's my code :这是我的代码:

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

I tried this.$$.nameInput.focus();我试过this.$$.nameInput.focus(); and this.$els.nameInput.focus();this.$els.nameInput.focus(); for what I could find online to target the focus, but this.$$ is undefined, and this.$els is empty.对于我可以在网上找到的焦点,但是this.$$是未定义的,并且this.$els是空的。

If that can help, I'm using vue.js v1.0.15如果有帮助,我正在使用 vue.js v1.0.15

Thank you for your help.谢谢您的帮助。

In vue 2.x you can solve it with a directive .在 vue 2.x 中,您可以使用指令来解决它。

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

Then you can use v-focus attribute on inputs and other elements:然后您可以在输入和其他元素上使用v-focus属性:

<input v-focus>

Another solution using Vue 2.x and ref .另一个使用 Vue 2.x 和ref的解决方案。

You can use the ref/$refs attribute to target your input and focus it.您可以使用ref/$refs属性来定位您的输入并将其聚焦。

In the example a simple method is used which can target the inputs using the ref attribute supplied to the inputs.在示例中,使用了一个简单的方法,该方法可以使用提供给输入的 ref 属性来定位输入。 Then access the $refs property on your instance to get a reference to the DOM element.然后访问实例上的$refs属性以获取对 DOM 元素的引用。

<script>
export default {
    // ...
  mounted: function () {
    this.focusInput('nameInput');
  },
  methods: {
    // This is the method that focuses the element
    focusInput: function ( inputRef ) {
      // $refs is an object that holds the DOM references to your inputs
      this.$refs[inputRef].focus();
    },

    search: function (event) {
      this.focusInput('domainInput');
    },
  }
}
</script>
<template>
  <form method="post" action="" v-on:submit.prevent="search">
    <input type="text" placeholder="Person name" required v-model="name" ref="nameInput" />
    <input type="text" placeholder="Company" required v-model="company" ref="domainInput" />
    <input type="submit" value="Search" class="btn show-m" />
  </form>
</template>

This solution is best for a one off situation or for a reusable component.此解决方案最适合一次性情况或可重用组件。 For a more global approach the directive is the way to go.对于更全球化的方法,指令是要走的路。

Setting focus inside a child element在子元素内设置焦点

(for those of you that struggled for hours like me) (对于那些像我一样挣扎了几个小时的人)

Parent:家长:

<template>
  <div @click="$refs.theComponent.$refs.theInput.focus()">
    <custom-input ref="theComponent"/>
  </div>
</template>

Child ( CustomInput.vue ):孩子( CustomInput.vue ):

<template>
  <input ref="theInput"/>
</template>

There are a couple of issues.有几个问题。

First of all, v-el s are defined like this:首先v-el的定义如下:

<input v-el:input-element/>

That'll turn the variable to a camelCase in the code.这会将变量转换为代码中的 camelCase。 You can read up more on this weird functionality here .您可以在此处阅读有关此奇怪功能的更多信息。

Other than that, you should be able to access the variable through this.$els.inputElement .除此之外,您应该能够通过this.$els.inputElement访问该变量。 Mind you, it will only appear in the component that you're defining that element (or the main app itself, if you defined it there).请注意,它只会出现在您定义该元素的组件中(或主应用程序本身,如果您在那里定义它)。

Secondly , the automatic focusing does not seem to be working on Firefox (43.0.4), at least on my machine.其次,自动对焦似乎不适用于 Firefox (43.0.4),至少在我的机器上是这样。 Everything works great on Chrome, and focuses as expected.一切都在 Chrome 上运行良好,并且按预期聚焦。

Using ref I managed to focus an Input on mounted like this.使用ref我设法将输入集中在这样的mounted

Template :模板 :

 <b-form-input  v-model="query" ref="searchInput" ></b-form-input>

Javascript : Javascript:

  mounted(){
    this.$refs.searchInput.$el.focus()
  }

Vue 3.x Vue 3.x

Use a custom directive.使用自定义指令。

app.directive('focus', {
    mounted(el) { 
      el.focus() 
    }
})

Here is how you use it:以下是你如何使用它:

Step 1:步骤1:

// main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)

 app.directive('focus', {
     mounted(el) { // When the bound element is inserted into the DOM...
       el.focus() // Focus the element
     }
 })

/* Optional: 
   Add a slight delay if the input does not focus.

app.directive('focus', {
    mounted(el) { // When the bound element is inserted into the DOM...
        setTimeout(() => {
            el.focus() // Focus the element
        }, 500)
    }
}) */

await router.isReady()
app.mount('#app')

Then in your component:然后在您的组件中:

Step 2:第2步:

// MyInput.vue

<input v-focus>

Vue docs Vue 文档

According to vue 2.x, you can also register "directive" locally in component to get autofocus.根据vue 2.x,你也可以在组件本地注册“指令”来获得自动对焦。

just write directive in component:只需在组件中编写指令:

export default {
  directives: { focus: {
    inserted: function (el) {
    el.focus()
    }
  }
  }
}

Then in a template, you can use the new v-focus attribute on any element, like this:然后在模板中,您可以在任何元素上使用新的 v-focus 属性,如下所示:

<input type="text" v-focus>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM