我正在尝试在 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 许可协议
在 vue 2.x 中你可以用一个 指令 来解决它。
然后你可以在输入和其他元素上使用
v-focus
属性: