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

I tried this.$$.nameInput.focus(); and this.$els.nameInput.focus(); for what I could find online to target the focus, but this.$$ is undefined, and this.$els is empty.

如果有帮助,我正在使用 vue.js v1.0.15

谢谢您的帮助。

原文由 Cyril N. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 481
2 个回答

在 vue 2.x 中你可以用一个 指令 来解决它。

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

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

 <input v-focus>

原文由 Lukasz Wiktor 发布,翻译遵循 CC BY-SA 4.0 许可协议

另一个使用 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>

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

此解决方案最适合一次性情况或可重用组件。对于更全局的方法,指令是可行的方法。

原文由 hitautodestruct 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题