安装时自动对焦输入(Vue)- iOS

新手上路,请多包涵

当 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 许可协议

阅读 311
2 个回答

我希望你现在一定已经找到了解决方案。

但我只是想为像我这样的其他新用户添加这个。

 mounted () {
    this.$refs.focusMe.focus()       // sometime this doesn't work.
  }

尝试添加这个。

 this.$nextTick(() => this.$refs.focusMe.focus())

有关更多信息,请查看

编辑:14/06/2022

Prashant 的 回答也帮助我更深入地理解了 nextTick。

nextTick 允许您在更改一些数据之后执行代码,并且 Vue.js 已根据您的数据更改更新虚拟 DOM,但在浏览器在页面上呈现该更改之前。

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

我建议在该字段上触发点击事件而不是焦点

this.showText = !this.showText;
this.$nextTick(function () {
    this.$refs.dummykeyboard.click();
})

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

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏