uni-app 基础表单组件 input 设置为密码类型时,会吞掉默认值
uni-app 基础表单组件 input 设置为密码类型时,会吞掉默认值
类别 | 信息 |
---|---|
产品分类 | uniapp/App |
PC开发环境 | Windows |
PC版本号 | win11 |
HBuilderX类型 | 正式 |
HBuilderX版本 | 4.08 |
手机系统 | Android |
手机版本号 | Android 14 |
手机厂商 | 魅族 |
手机机型 | MEIZU 20 |
页面类型 | nvue |
Vue版本 | vue3 |
打包方式 | 云端 |
项目创建方式 | HBuilderX |
示例代码:
<code>
<input v-else :type="type === 'password' ? 'text' : type" class="uni-easyinput__content-input" :style="inputStyle"
:name="name" :value="val" :password="!showPassword && type === 'password'" :placeholder="placeholder"
:placeholderStyle="placeholderStyle" placeholder-class="uni-easyinput__placeholder-class" :disabled="disabled"
:maxlength="inputMaxlength" :focus="focused" :confirmType="confirmType" :cursor-spacing="cursorSpacing"
:adjust-position="adjustPosition" @focus="_Focus" @blur="_Blur" @input="onInput" @confirm="onConfirm"
@keyboardheightchange="onkeyboardheightchange" />
<!-- #endif -->
</code>
操作步骤:
- 渲染一个密码输入框,绑定默认值,绑定input事件
预期结果:
- 预期默认值会正常显示
实际结果:
- 默认值被 input 事件传递的空值覆盖
bug描述:
- 基础表单组件 input 设置为密码类型时,会吞掉默认值,经检查,在安卓机型下,input组件的 input 事件会自动触发,以空值覆盖默认值。
- 另外,uni-ui 的 easyinput 组件也因为没有区分app的环境,将多端代码写在一起,导致一旦设置了 password 属性的值,点击非密码类型的表单都会弹出字符类型的键盘,代码如下贴在下方,如果直接设置
更多关于uni-app 基础表单组件 input 设置为密码类型时,会吞掉默认值的实战教程也可以访问 https://www.itying.com/category-93-b0.html
<input :value=“loginForm.password” type=“password” @input=“input” />
const input = (event) => {
let value = event.detail.value;
console.log(‘val’, value);
loginForm.value.password = value
}
以上是最基础的复现例子
更多关于uni-app 基础表单组件 input 设置为密码类型时,会吞掉默认值的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在 uni-app
中使用 <input>
组件时,如果将 type
设置为 password
,确实会出现默认值被“吞掉”的情况。这是因为 type="password"
的输入框在大多数浏览器中会自动清除默认值,以避免密码泄露。
解决方法
-
使用
v-model
动态绑定值: 通过v-model
动态绑定输入框的值,确保在输入框类型切换时,值不会丢失。<template> <view> <input v-model="password" :type="inputType" placeholder="请输入密码" /> <button @click="toggleInputType">切换输入类型</button> </view> </template> <script> export default { data() { return { password: 'defaultPassword', inputType: 'password' }; }, methods: { toggleInputType() { this.inputType = this.inputType === 'password' ? 'text' : 'password'; } } }; </script>
-
使用
placeholder
替代默认值: 如果你希望在输入框为空时显示提示信息,可以使用placeholder
属性。<template> <view> <input type="password" placeholder="请输入密码" /> </view> </template>
-
在
mounted
生命周期中手动设置值: 如果你确实需要在type="password"
的输入框中显示默认值,可以在mounted
生命周期中手动设置输入框的值。<template> <view> <input ref="passwordInput" type="password" placeholder="请输入密码" /> </view> </template> <script> export default { mounted() { this.$refs.passwordInput.value = 'defaultPassword'; } }; </script>