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

JavaScript Vue.js

凯西里

2020-04-07

我正在尝试在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

谢谢您的帮助。

第4058篇《在vue.js中设置输入元素的焦点》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
飞云 2020.04.07

根据vue 2.x,您还可以在组件中本地注册“指令”以获取自动聚焦。

只需在组件中编写指令:

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

然后在模板中,可以在任何元素上使用新的v-focus属性,如下所示:

<input type="text" v-focus>
猪猪小小 2020.04.07

有几个问题。

首先v-el的定义如下:

<input v-el:input-element/>

这会将变量转换为代码中的camelCase。您可以在此处阅读有关此奇怪功能的更多信息

除此之外,您还应该可以通过访问变量this.$els.inputElement请注意,它只会出现在您正在定义该元素的组件中(或主应用程序本身,如果您在其中定义的话)。

其次,至少在我的机器上,自动对焦似乎在Firefox(43.0.4)上不起作用。一切在Chrome上都能正常运行,并且可以按预期聚焦。

小宇宙 2020.04.07

在子元素内设置焦点

(对于那些像我一样努力奋斗了几个小时的人)

上级:

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

子(CustomInput.vue):

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android