uniapp密码组件隐藏
时间: 2025-02-10 08:29:31 浏览: 31
### 创建隐藏密码显示的自定义组件
在 UniApp 中创建用于隐藏密码显示的自定义组件可以通过多种方式实现。一种常见的方式是利用 `input` 组件并结合 Vue 的双向绑定特性来控制输入框内的内容是否可见。
#### 使用内置属性构建简单版本
对于简单的场景,可以仅依赖于 `<input>` 或者 `<uni-easyinput>` 提供的 `password` 属性:
```html
<template>
<view>
<!-- 密码输入框 -->
<input type="text" v-model="value" :password="isPasswordVisible"/>
<!-- 切换按钮 -->
<button @click="toggleVisibility">切换</button>
</view>
</template>
<script>
export default {
data() {
return {
value: '',
isPasswordVisible: true,
};
},
methods: {
toggleVisibility() {
this.isPasswordVisible = !this.isPasswordVisible;
}
}
}
</script>
```
此代码片段展示了如何通过点击按钮改变 `isPasswordVisible` 变量的状态从而达到切换明文/密文的效果[^1]。
#### 构建更复杂的自定义组件
如果需求更加复杂,则建议封装成独立的组件以便重用和维护。下面是一个稍微高级一点的例子,它不仅实现了基本的功能还增加了样式定制选项以及事件触发机制。
##### 定义新组件结构
首先,在项目中的合适位置新建文件夹作为组件存放路径,并按照如下模板编写 `.vue` 文件:
```html
<!-- components/passwordInput.vue -->
<template>
<view class="custom-password-input">
<input
:type="currentType"
v-bind="$attrs"
v-on="listeners"
placeholder-class="placeholder-style"
password="{{!showPwd}}"
confirm-type="done"
focus=""
cursor-spacing="80"
maxlength="20"
auto-blur="">
<button size="mini" hover-class="none" @tap="handleEyeClick">{{ showPwd ? 'Hide' : 'Show' }}</button>
</view>
</template>
<script>
import './index.css';
export default {
props: ['modelValue'],
computed:{
currentType(){
return this.showPwd?'text':'password';
},
listeners () {
const vm = this;
// 将父作用域的监听器返回给子组件
return Object.assign({}, this.$listeners, {
input(event){
let val=event.detail.value;
vm.$emit('update:modelValue',val);
}
});
}
},
data() {
return {
showPwd:false,
}
},
watch: {
modelValue(newVal) {
console.log(`new Value:${ newVal}`);
}
},
methods: {
handleEyeClick() {
this.showPwd=!this.showPwd;
}
}
};
</script>
<style lang="scss" scoped>
.custom-password-input{
display:flex;
align-items:center;
.placeholder-style{
color:#ccc!important;
}
button{
margin-left:10px;
}
}
</style>
```
上述代码中引入了一个名为 `passwordInput` 的自定义组件,该组件允许开发者轻松集成到页面内任何地方的同时也提供了良好的用户体验[^4]。
阅读全文