uniapp 页面初始化如何获取input焦点

在uniapp中,页面初始化时如何自动获取input输入框的焦点?我已经尝试在onLoad和onReady生命周期里调用this.$refs.input.focus(),但都没有效果。请问正确的实现方式是什么?需要用到哪些API或特殊处理?

2 回复

onReady 生命周期中,使用 this.$refs.input.focus() 获取焦点。需要给 input 设置 ref="input"


在 UniApp 中,页面初始化时获取 input 焦点可以通过以下方法实现:

方法一:使用 this.$nextTickuni.createSelectorQuery()

在页面 onReady 生命周期中,使用 this.$nextTick 确保 DOM 渲染完成,然后通过 uni.createSelectorQuery() 获取 input 元素并聚焦。

示例代码:

export default {
  data() {
    return {
      inputValue: ''
    }
  },
  onReady() {
    this.$nextTick(() => {
      const query = uni.createSelectorQuery().in(this);
      query.select('#myInput').node((res) => {
        const input = res.node;
        input.focus();
      }).exec();
    });
  }
}
<template>
  <view>
    <input id="myInput" v-model="inputValue" type="text" />
  </view>
</template>

方法二:使用 focus 属性(H5 和部分平台支持)

在 input 组件上直接设置 focus 属性为 true,但注意兼容性(H5 和微信小程序支持较好)。

示例代码:

<template>
  <view>
    <input v-model="inputValue" :focus="true" type="text" />
  </view>
</template>

注意事项:

  1. 平台差异focus 属性在部分平台(如 App)可能不支持,建议优先使用方法一。
  2. 生命周期:确保在 onReadymounted 后执行聚焦操作,避免 DOM 未渲染。
  3. 组件封装:若使用自定义组件,需通过 ref 调用子组件的聚焦方法。

根据需求选择合适的方法,推荐使用方法一以兼容更多平台。

回到顶部