vue2+vant-ui van-field输入框显示隐藏密码组件封装(移动端项目、H5项目)

663 阅读1分钟

一、需求

不管是什么项目,通常会有这种需求,密码输入的时候点击要显示密码再次点击隐藏

二、最终效果

在这里插入图片描述

三、参数配置

继承 van-field所有API(Attributes(Props)、Events、Slots) 新增了属性:showPassword 默认不显示

四、具体代码

<template>
  <van-field class="t_vant_field" v-bind="$attrs" :type="passwordType" v-on="$listeners">
    <template slot="right-icon" v-if="showPassword">
      <span class="solts" @click="switchPasswordType">
        <van-icon name="eye" v-if="passwordType==='password'" />
        <van-icon name="closed-eye" v-else />
      </span>
    </template>
    <!-- 遍历子组件非作用域插槽,并对父组件暴露 -->
    <template v-for="(index, name) in $slots" v-slot:[name]>
      <slot :name="name" />
    </template>
    <!-- 遍历子组件作用域插槽,并对父组件暴露 -->
    <template v-for="(index, name) in $scopedSlots" v-slot:[name]="data">
      <slot :name="name" v-bind="data"></slot>
    </template>
  </van-field>
</template>

<script>
export default {
  name: 'TVanField',
  props: {
    showPassword: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'text'
    }
  },
  data() {
    return {
      passwordType: this.type
    }
  },
  methods: {
    switchPasswordType() {
      this.passwordType = this.passwordType === 'password' ? 'text' : 'password'
    }
  }
}
</script>
<style lang="scss" scoped>
.t_vant_field {
  .van-field__right-icon {
    .solts {
      right: -15px;
    }
  }
}
</style>

五、相关文章

基于ElementUi&antdUi再次封装基础组件文档


vue3+ts基于Element-plus再次封装基础组件文档