uni-app 从下级页面返回后 input不能手动执行获焦

uni-app 从下级页面返回后 input不能手动执行获焦

操作步骤:

  • 从下一页面返回到上级页面后,上级页面中的input设置手动执行获焦失败,但是键盘抬起

预期结果:

  • 从下一页面返回到上级页面后,上级页面中的input能设置手动执行获焦并键盘抬起

实际结果:

  • 第一次进入质量检查页面时,上面的input手动获焦成功。然后点击其他按钮跳走页面,再返回到质量检查页面时,input获焦就不成功了,但是键盘有抬起

bug描述:

  • 用uni.navigateBack返回上级页面后,onshow时上级页面不能手动执行获焦。上级页面onShow的代码如下:
    • uni.hideKeyboard();
    • this.isFocus = false;
    • this.$nextTick(() => {
      • this.isFocus = true;
    • })
  • 下面的附件中有视频操作:
    • 第一次进入质量检查页面时,上面的input手动获焦成功。然后点击其他按钮跳走页面,再返回到质量检查页面时,input获焦就不成功了,但是键盘有抬起
开发环境 版本号 项目创建方式
Windows 10 HBuilderX
Android 9.0
3 回复

请问解决了吗?看你的链接没有给出解决方案

在 uni-app 中,从下级页面返回后,input 元素无法手动获取焦点的问题,通常是由于页面生命周期或焦点管理的问题导致的。以下是一些可能的解决方案:

1. 使用 nextTick

在页面返回后,可能需要等待 DOM 更新完成后再尝试获取焦点。可以使用 this.$nextTick 来确保 DOM 更新完成后再执行获取焦点的操作。

onShow() {
  this.$nextTick(() => {
    this.$refs.input.focus();
  });
}

2. 使用 setTimeout

有时候,使用 setTimeout 延迟执行获取焦点的操作也可以解决问题。

onShow() {
  setTimeout(() => {
    this.$refs.input.focus();
  }, 100);
}

3. 确保 input 元素存在

确保在获取焦点时,input 元素已经存在于 DOM 中。如果 input 元素是通过条件渲染显示的,确保在获取焦点之前,条件已经满足。

onShow() {
  if (this.showInput) {
    this.$nextTick(() => {
      this.$refs.input.focus();
    });
  }
}

4. 使用 uni.pageScrollTo

在某些情况下,页面滚动可能会影响焦点的获取。可以尝试在获取焦点前将页面滚动到合适的位置。

onShow() {
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0,
    complete: () => {
      this.$nextTick(() => {
        this.$refs.input.focus();
      });
    }
  });
}

5. 检查 inputdisabledreadonly 属性

确保 input 元素没有被禁用或设置为只读。

<input ref="input" :disabled="isDisabled" :readonly="isReadonly" />

6. 使用 focus 方法

确保你使用的是正确的 focus 方法。在 uni-app 中,input 元素的 focus 方法是通过 ref 来调用的。

this.$refs.input.focus();

7. 检查页面生命周期

确保你在正确的生命周期钩子中执行获取焦点的操作。通常,onShow 是一个合适的选择。

onShow() {
  this.$nextTick(() => {
    this.$refs.input.focus();
  });
}

8. 使用 uni.navigateBacksuccess 回调

如果你是通过 uni.navigateBack 返回页面的,可以在 success 回调中执行获取焦点的操作。

uni.navigateBack({
  delta: 1,
  success: () => {
    this.$nextTick(() => {
      this.$refs.input.focus();
    });
  }
});

9. 检查键盘弹出问题

在某些情况下,键盘的弹出可能会影响焦点的获取。可以尝试在获取焦点后手动弹出键盘。

onShow() {
  this.$nextTick(() => {
    this.$refs.input.focus();
    uni.showKeyboard({
      defaultText: '',
      confirmHold: false
    });
  });
}

10. 使用 uni.setNavigationBarTitle

在某些情况下,设置导航栏标题可能会触发页面重新渲染,从而解决焦点问题。

onShow() {
  uni.setNavigationBarTitle({
    title: '页面标题'
  });
  this.$nextTick(() => {
    this.$refs.input.focus();
  });
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!