当前位置:首页 > VUE

vue密码显示隐藏实现

2026-02-24 11:00:06VUE

实现密码显示/隐藏功能

在Vue中实现密码显示与隐藏功能,可以通过结合v-modelv-on指令来控制输入框的类型属性。

模板部分代码示例:

<template>
  <div class="password-input">
    <input 
      :type="showPassword ? 'text' : 'password'" 
      v-model="password" 
      placeholder="请输入密码"
    >
    <button @click="togglePassword">
      {{ showPassword ? '隐藏' : '显示' }}
    </button>
  </div>
</template>

脚本部分代码示例:

<script>
export default {
  data() {
    return {
      password: '',
      showPassword: false
    }
  },
  methods: {
    togglePassword() {
      this.showPassword = !this.showPassword
    }
  }
}
</script>

使用图标代替文本按钮

可以使用字体图标库(如Font Awesome)来提升用户体验。

安装Font Awesome:

vue密码显示隐藏实现

npm install @fortawesome/fontawesome-free

使用图标示例:

<template>
  <div class="password-input">
    <input 
      :type="showPassword ? 'text' : 'password'" 
      v-model="password"
    >
    <i 
      class="fas" 
      :class="showPassword ? 'fa-eye-slash' : 'fa-eye'" 
      @click="togglePassword"
    ></i>
  </div>
</template>

添加样式增强视觉效果

为密码输入框添加基本样式可以改善外观。

样式示例:

vue密码显示隐藏实现

<style scoped>
.password-input {
  position: relative;
  display: inline-block;
}

.password-input input {
  padding: 8px;
  padding-right: 30px;
}

.password-input i {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}
</style>

使用第三方组件库

如果需要快速实现,可以使用现成的UI组件库如Element UI或Vuetify。

Element UI示例:

<template>
  <el-input
    v-model="password"
    :type="showPassword ? 'text' : 'password'"
    placeholder="请输入密码"
  >
    <template #suffix>
      <i 
        class="el-icon-view" 
        @click="showPassword = !showPassword"
      ></i>
    </template>
  </el-input>
</template>

表单验证集成

可以结合Vuelidate或VeeValidate进行表单验证。

Vuelidate集成示例:

import { required, minLength } from 'vuelidate/lib/validators'

export default {
  data() {
    return {
      password: '',
      showPassword: false
    }
  },
  validations: {
    password: {
      required,
      minLength: minLength(6)
    }
  }
}

标签: 密码vue
分享给朋友:

相关文章

vue实现条件判断

vue实现条件判断

Vue 条件判断实现方法 Vue 提供了多种方式实现条件判断,可以根据不同场景选择合适的方式。 v-if / v-else-if / v-else 这是 Vue 中最常用的条件渲染指令,根据表达式的…

vue状态管理怎么实现

vue状态管理怎么实现

Vue 状态管理实现方法 使用 Vuex(官方推荐) Vuex 是 Vue 的官方状态管理库,适合中大型应用。 安装 Vuex: npm install vuex --save 创建 Store 示…

vue实现pie

vue实现pie

Vue 实现饼图 在 Vue 中实现饼图通常可以通过第三方图表库(如 ECharts、Chart.js 或 Highcharts)来完成。以下是使用 ECharts 和 Chart.js 的两种常见方…

vue实现addclass

vue实现addclass

Vue 实现动态添加 class 的方法 在 Vue 中动态添加 class 可以通过多种方式实现,以下是常见的几种方法: 使用对象语法 通过绑定一个对象到 :class,可以动态切换 class…

vue实现评分

vue实现评分

Vue 实现评分功能 使用组件库实现 安装 element-ui 或 ant-design-vue 这类 UI 库,它们已经内置了评分组件。 以 element-ui 为例: <templa…

vue实现爬虫

vue实现爬虫

Vue 实现爬虫的基本思路 Vue.js 本身是一个前端框架,主要用于构建用户界面。要实现爬虫功能,通常需要结合后端技术或浏览器自动化工具。以下是几种常见的方法: 方法一:Vue + Node.js…