Vue 3组合式API中密码显示/隐藏按钮功能异常问题
Vue 3组合式API实现独立密码显示/隐藏按钮
问题核心是你用了同一个响应式状态控制两个输入框的显示状态,导致点击按钮时两者同时切换。解决方法是给密码和确认密码分别设置独立的状态变量:
实现代码
<template> <div> <div class="input-group"> <input :type="showPassword ? 'text' : 'password'" placeholder="输入密码" > <button @click="showPassword = !showPassword"> {{ showPassword ? '隐藏' : '显示' }} </button> </div> <div class="input-group"> <input :type="showConfirmPassword ? 'text' : 'password'" placeholder="确认密码" > <button @click="showConfirmPassword = !showConfirmPassword"> {{ showConfirmPassword ? '隐藏' : '显示' }} </button> </div> </div> </template> <script setup> import { ref } from 'vue' // 为密码和确认密码分别定义独立的状态 const showPassword = ref(false) const showConfirmPassword = ref(false) </script> <style scoped> .input-group { margin: 10px 0; display: flex; gap: 8px; } </style>
关键说明
- 用两个独立的
ref变量showPassword和showConfirmPassword分别控制对应输入框的显示状态。 - 每个按钮只切换自身对应的状态变量,实现两个输入框的显示/隐藏操作互不影响。
- 输入框的
type属性通过三元表达式动态切换:状态为true时显示明文(text),为false时显示密文(password)。
内容的提问来源于stack exchange,提问作者coochie
相关产品推荐
相关产品推荐

