You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 08:46:25