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

Cyr*_* N. 12 javascript 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>
Run Code Online (Sandbox Code Playgroud)

我尝试过this.$$.nameInput.focus();,this.$els.nameInput.focus();我可以在网上找到目标焦点,但是this.$$未定义,并且this.$els是空的.

如果这可以帮助,我正在使用vue.js v1.0.15

谢谢您的帮助.

Luk*_*tor 34

在vue 2.x中,您可以使用指令解决它.

Vue.directive('focus', {
    inserted: function (el) {
        el.focus()
    }
})
Run Code Online (Sandbox Code Playgroud)

然后,您可以v-focus在输入和其他元素上使用属性:

<input v-focus>
Run Code Online (Sandbox Code Playgroud)


hit*_*uct 6

使用Vue 2.x和的另一种解决方案ref

您可以使用该ref/$refs属性来定位输入并使其集中。

在该示例中,使用了一种简单的方法,该方法可以使用提供给输入的ref属性将输入作为目标。然后访问$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>
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)