我想在 Vue 组件出现时触发输入框聚焦(从而弹出键盘)。
它不起作用iOS
.
我尝试使用 Vue 的示例指令(here https://v2.vuejs.org/v2/guide/custom-directive.html)和 HTML5autoFocus
但都不起作用。
我在沙箱中创建了这个示例(https://codesandbox.io/s/lw321wqkm https://codesandbox.io/s/lw321wqkm).
FWIW,我不认为这是 JS 限制,因为我已经看到了示例工作(例如 React Native Web 使用autoFocus
- 参见示例 https://codesandbox.io/s/zrn8jooy1m)
父组件
<template>
<div>
<TextComp v-if='showText' />
<button @click='showText = !showText'> Show/hide input </button>
</div>
</template>
...
子组件
<template>
<div>
<input ref='focusMe' type='text'/>
</div>
</template>
<script>
export default {
name: 'TextComp',
mounted () {
this.$refs.focusMe.focus()
}
}
</script>
我希望你现在一定已经找到了解决方案。
但我只是想为像我这样的其他新用户添加这个。
mounted () {
this.$refs.focusMe.focus() // sometime this doesn't work.
}
尝试添加这个。
this.$nextTick(() => this.$refs.focusMe.focus())
欲了解更多信息,请检查this https://v2.vuejs.org/v2/api/#Vue-nextTick
编辑:2022 年 6 月 14 日
普拉尚特 https://stackoverflow.com/a/47636157/5375291答案也帮助我更深入地理解了nextTick。
nextTick 允许您在更改一些数据并且 Vue.js 根据您的数据更改更新虚拟 DOM 之后、但在浏览器在页面上呈现该更改之前执行代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)