uni-app u-view中 u--input 切换type时,input框内有数据时光标bug

uni-app u-view中 u–input 切换type时,input框内有数据时光标bug

开发环境 版本号 项目创建方式
PC Windows 10 1909 CLI 2

示例代码:

<template> <view class="content"> <text>密码:</text> <u--input ref="passwordRef" v-model="password" placeholder="请输入密码" clearable :type="type" border="bottom" > <template slot="suffix"> <u-icon name="eye" size="40" v-if="isPassword" @click="changeShowPwd" /> <u-icon name="eye-fill" size="40" v-if="!isPassword" @click="changeShowPwd" /> </template> </u--input> </view> </template> <script> export default { data() { return { password: '' ,// 密码 isPassword: true, //密码是否显示 type:"password" } }, mounted() {}, methods: { changeShowPwd() { this.isPassword = !this.isPassword if(this.isPassword){ this.type="text" }else{ this.type="password" } console.log(this.type,'type') } } } </script> <style lang="scss" scoped> // ROOT .login-root-view { flex: 1; .content { flex: 1; flex-direction: row; padding: 0 50rpx 0 40rpx; } </style>
4 回复

上传完整的可以复现的demo,方便排查,u–input哪里来的

··· ①附件文件是示例文件(整个项目),下载的是uniapp官方的示例文件 ②demo在文件的路径 pages/tabBar/component/component (用自定义基座,安卓模拟器打开后是首页) ③ u–input来源是 uView 这个UI框架 ···

uni-app 中使用 uView 组件库时,u--input 组件在切换 type 属性时,如果输入框内有数据,可能会出现光标位置不正确的 Bug。这是由于 input 组件在切换 type 时,浏览器或小程序底层可能会重新渲染输入框,导致光标位置丢失或重置。

解决方案

  1. 手动保存和恢复光标位置: 在切换 type 之前,手动保存当前光标的位置,切换 type 后再恢复光标位置。

    <template>
      <view>
        <u--input
          v-model="inputValue"
          :type="inputType"
          ref="inputRef"
          @focus="handleFocus"
        />
        <button @click="toggleInputType">切换输入类型</button>
      </view>
    </template>
    
    <script>
    export default {
      data() {
        return {
          inputValue: '',
          inputType: 'text',
          cursorPosition: 0,
        };
      },
      methods: {
        handleFocus(event) {
          this.cursorPosition = event.detail.cursor;
        },
        toggleInputType() {
          // 保存光标位置
          this.cursorPosition = this.$refs.inputRef.cursor;
    
          // 切换输入类型
          this.inputType = this.inputType === 'text' ? 'password' : 'text';
    
          // 恢复光标位置
          this.$nextTick(() => {
            this.$refs.inputRef.setCursor(this.cursorPosition);
          });
        },
      },
    };
    </script>
  2. 使用 key 强制重新渲染: 通过给 u--input 组件绑定一个唯一的 key,在切换 type 时改变 key 值,强制组件重新渲染。这样可以避免光标位置问题,但会丢失当前输入框的状态。

    <template>
      <view>
        <u--input
          v-model="inputValue"
          :type="inputType"
          :key="inputType"
        />
        <button @click="toggleInputType">切换输入类型</button>
      </view>
    </template>
    
    <script>
    export default {
      data() {
        return {
          inputValue: '',
          inputType: 'text',
        };
      },
      methods: {
        toggleInputType() {
          this.inputType = this.inputType === 'text' ? 'password' : 'text';
        },
      },
    };
    </script>
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!