当 Vue 组件出现时,我想触发输入框聚焦(从而弹出键盘)。
它不适用于 iOS
。
我尝试使用 Vue 的示例指令( 此处)和 HTML5 autoFocus
但均无效。
我在沙箱 ( https://codesandbox.io/s/lw321wqkm ) 中创建了这个示例。
FWIW,我不认为这是一个 JS 限制,因为我已经看到示例工作(例如 React Native Web 使用 autoFocus
- 请参见示例)
父组件
<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>
原文由 Ycon 发布,翻译遵循 CC BY-SA 4.0 许可协议
我希望你现在一定已经找到了解决方案。
但我只是想为像我这样的其他新用户添加这个。
尝试添加这个。
有关更多信息,请查看 此
编辑:14/06/2022
Prashant 的 回答也帮助我更深入地理解了 nextTick。
nextTick 允许您在更改一些数据之后执行代码,并且 Vue.js 已根据您的数据更改更新虚拟 DOM,但在浏览器在页面上呈现该更改之前。