输入密码、显示或隐藏它,并在原生表单里使用它。

Password Input 是一个原生密码字段,带一个显示和隐藏已输入内容的按钮。它让光标留在原处,让密码管理器提供正确的密码,并在表单提交时再次隐藏密码。

<script setup lang="ts">
import { EyeIcon, EyeOffIcon } from "@lucide/vue"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import {
  PasswordInput,
  PasswordInputControl,
  PasswordInputToggle,
} from "@ui-sdk/vue/password-input"
</script>

<template>
  <Field name="password">
    <FieldLabel>Password</FieldLabel>
    <PasswordInput>
      <PasswordInputControl />
      <PasswordInputToggle v-slot="{ state }" aria-label="Show password">
        <EyeOffIcon v-if="state.visible" aria-hidden="true" />
        <EyeIcon v-else aria-hidden="true" />
      </PasswordInputToggle>
    </PasswordInput>
    <FieldDescription>Use at least 8 characters.</FieldDescription>
  </Field>
</template>
输入密码,然后选择 Show password 显示或隐藏它。点击切换按钮会让光标留在输入框里。用键盘时,按 Tab 到切换按钮,再按 Space 或 Enter。

安装

npm install @ui-sdk/vue @ui-sdk/core

组合

用下面的组合构建 PasswordInput:

PasswordInput
├── PasswordInputControl
└── PasswordInputToggle

PasswordInput 保存值和可见性状态。PasswordInputControl 渲染原生输入框;PasswordInputToggle 渲染显示和隐藏它的按钮。切换按钮在 password 和 text 之间切换输入框,并且是 type="button",所以在输入框里按 Enter 仍然会提交表单。

把 name、form、required、disabled 和 read-only 这样的表单选项放在 PasswordInput 上。把 placeholder 或 id 这样的其他原生输入属性放在 PasswordInputControl 上。

用法

导入部件并把它们组合起来:

<script setup lang="ts">
import {
  PasswordInput,
  PasswordInputControl,
  PasswordInputToggle,
} from "@ui-sdk/vue/password-input"
</script>

<template>
  <PasswordInput name="password">
    <PasswordInputControl aria-label="Password" />
    <PasswordInputToggle aria-label="Show password">Show</PasswordInputToggle>
  </PasswordInput>
</template>

新密码

创建或修改密码时,在根部件上使用 auto-complete="new-password"。它告诉浏览器和密码管理器要提供哪种密码。登录时的默认值是 current-password。

示例从当前值推导出一份检查清单。这些规则属于示例;组件不强制任何密码策略。

<script setup lang="ts">
import { CheckIcon, EyeIcon, EyeOffIcon, XIcon } from "@lucide/vue"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  PasswordInput,
  PasswordInputControl,
  PasswordInputToggle,
} from "@ui-sdk/vue/password-input"
import { ref } from "vue"

const rules = [
  {
    label: "At least 8 characters",
    test: (password: string) => password.length >= 8,
  },
  { label: "A number", test: (password: string) => /\d/.test(password) },
  {
    label: "An uppercase and a lowercase letter",
    test: (password: string) =>
      /[a-z]/.test(password) && /[A-Z]/.test(password),
  },
]

const password = ref("")
</script>

<template>
  <Field name="new-password">
    <FieldLabel>Create a password</FieldLabel>
    <PasswordInput
      :value="password"
      auto-complete="new-password"
      @value-change="(value: string) => (password = value)"
    >
      <PasswordInputControl />
      <PasswordInputToggle v-slot="{ state }" aria-label="Show password">
        <EyeOffIcon v-if="state.visible" aria-hidden="true" />
        <EyeIcon v-else aria-hidden="true" />
      </PasswordInputToggle>
    </PasswordInput>
    <ul data-slot="stack" aria-label="Password requirements">
      <template v-for="rule in rules" :key="rule.label">
        <li v-if="rule.test(password)" data-slot="row">
          <CheckIcon aria-hidden="true" />
          <span data-slot="visually-hidden">Done:</span>
          {{ rule.label }}
        </li>
        <li v-else data-slot="row">
          <XIcon aria-hidden="true" />
          <span data-slot="visually-hidden">To do:</span>
          {{ rule.label }}
        </li>
      </template>
    </ul>
  </Field>
</template>
输入密码,观察检查清单更新。试着加入数字和大小写字母,然后切换它的可见性。

一开始就可见

设置 default-visible 让文字一开始就可见,设置 default-value 提供初始值。对于需要有人读取或复制的 Wi-Fi 密码,这很有用。

<script setup lang="ts">
import { EyeIcon, EyeOffIcon } from "@lucide/vue"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import {
  PasswordInput,
  PasswordInputControl,
  PasswordInputToggle,
} from "@ui-sdk/vue/password-input"
</script>

<template>
  <Field name="wifi-password">
    <FieldLabel>Wi-Fi password</FieldLabel>
    <PasswordInput
      default-visible
      default-value="maple-orbit-42"
      auto-complete="new-password"
    >
      <PasswordInputControl />
      <PasswordInputToggle v-slot="{ state }" aria-label="Show password">
        <EyeOffIcon v-if="state.visible" aria-hidden="true" />
        <EyeIcon v-else aria-hidden="true" />
      </PasswordInputToggle>
    </PasswordInput>
    <FieldDescription
      >Guests read it from here, so it starts shown.</FieldDescription
    >
  </Field>
</template>
读取 Wi-Fi 密码,然后选择 Show password 隐藏它。再次选择它会显示值。

大写锁定

用 data-capslock 或部件的 capsLock 状态显示警告。输入框获得焦点时,它会随按键事件更新。示例为图标和警告预留了空间。

<script setup lang="ts">
import { EyeIcon, EyeOffIcon, LockIcon } from "@lucide/vue"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  PasswordInput,
  PasswordInputControl,
  PasswordInputToggle,
} from "@ui-sdk/vue/password-input"
</script>

<template>
  <Field name="password">
    <FieldLabel>Password</FieldLabel>
    <PasswordInput v-slot="{ state }">
      <PasswordInputControl />
      <span><LockIcon v-if="state.capsLock" aria-hidden="true" /></span>
      <PasswordInputToggle
        v-slot="{ state: toggle }"
        aria-label="Show password"
      >
        <EyeOffIcon v-if="toggle.visible" aria-hidden="true" />
        <EyeIcon v-else aria-hidden="true" />
      </PasswordInputToggle>
    </PasswordInput>
    <p data-slot="caps-lock">Caps Lock is on.</p>
  </Field>
</template>
聚焦 Password 并按 Caps Lock。大写锁定开启时警告会出现。关闭它或离开字段,警告就会隐藏。

禁用

在根部件、它的 Field 或包住它的字段集上设置 disabled,同时禁用输入框和切换按钮。这个值不会出现在表单提交里。

<script setup lang="ts">
import { EyeIcon, EyeOffIcon } from "@lucide/vue"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import {
  PasswordInput,
  PasswordInputControl,
  PasswordInputToggle,
} from "@ui-sdk/vue/password-input"
</script>

<template>
  <Field disabled name="password">
    <FieldLabel>Password</FieldLabel>
    <PasswordInput default-value="hunter22">
      <PasswordInputControl />
      <PasswordInputToggle v-slot="{ state }" aria-label="Show password">
        <EyeOffIcon v-if="state.visible" aria-hidden="true" />
        <EyeIcon v-else aria-hidden="true" />
      </PasswordInputToggle>
    </PasswordInput>
    <FieldDescription
      >Your administrator manages this password.</FieldDescription
    >
  </Field>
</template>
试着编辑 Password 或按它的切换按钮。两个控件都被禁用,Tab 会跳过它们。

只读

当值可以读取但不能编辑时,设置 read-only。输入框仍然可以聚焦,切换按钮仍然可用,值也仍然参与表单提交。

<script setup lang="ts">
import { EyeIcon, EyeOffIcon } from "@lucide/vue"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import {
  PasswordInput,
  PasswordInputControl,
  PasswordInputToggle,
} from "@ui-sdk/vue/password-input"
</script>

<template>
  <Field name="recovery-key">
    <FieldLabel>Recovery key</FieldLabel>
    <PasswordInput read-only default-value="7Hq2-vX9p-Lm4c" auto-complete="off">
      <PasswordInputControl />
      <PasswordInputToggle v-slot="{ state }" aria-label="Show recovery key">
        <EyeOffIcon v-if="state.visible" aria-hidden="true" />
        <EyeIcon v-else aria-hidden="true" />
      </PasswordInputToggle>
    </PasswordInput>
    <FieldDescription
      >Keep it somewhere safe. You can show it, but not change
      it.</FieldDescription
    >
  </Field>
</template>
选择 Show recovery key 来读取它。试着在输入框里输入;它的值保持不变。

受控的可见性

用 v-model:visible 绑定可见性,并监听 @visible-change 获取详情。原因区分切换按钮的按压、表单提交、重置、页面隐藏,以及控制器动作。

控制台
<script setup lang="ts">
import { EyeIcon, EyeOffIcon } from "@lucide/vue"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  PasswordInput,
  PasswordInputControl,
  PasswordInputToggle,
} from "@ui-sdk/vue/password-input"
import { ref } from "vue"
import { useLog } from "./log"

const log = useLog()
const visible = ref(false)

function onVisibleChange(next: boolean, details: { reason: string }) {
  log(`${next ? "Shown" : "Hidden"} (${details.reason})`)
}
</script>

<template>
  <Field name="password">
    <FieldLabel>Password</FieldLabel>
    <PasswordInput v-model:visible="visible" @visible-change="onVisibleChange">
      <PasswordInputControl />
      <PasswordInputToggle v-slot="{ state }" aria-label="Show password">
        <EyeOffIcon v-if="state.visible" aria-hidden="true" />
        <EyeIcon v-else aria-hidden="true" />
      </PasswordInputToggle>
    </PasswordInput>
  </Field>
</template>
切换 Show password。控制台会记录每一次变更及其原因。

在变更回调里调用 details.cancel() 来拒绝一次可见性变更。表单提交期间,即使回调拒绝隐藏密码,原生输入框也会暂时变成密码字段。

控制器

创建 createPasswordInputController() 并作为 controller 传入,处理输入框之外的动作。读取或更改值、切换可见性,或聚焦输入框。写入会使用 imperative 原因。

控制台
<script setup lang="ts">
import { EyeIcon, EyeOffIcon } from "@lucide/vue"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  createPasswordInputController,
  PasswordInput,
  PasswordInputControl,
  PasswordInputToggle,
} from "@ui-sdk/vue/password-input"
import { useLog } from "./log"

const log = useLog()
const password = createPasswordInputController()

function suggest() {
  password.setValue("plum-kettle-orbit-42")
  password.setVisible(true)
}

function read() {
  log(
    `${password.getValue().length} characters, ${password.isVisible() ? "shown" : "hidden"}`
  )
}
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <button type="button" @click="suggest">Suggest</button>
      <button type="button" @click="password.toggleVisible()">Toggle</button>
      <button type="button" @click="password.clear()">Clear</button>
      <button type="button" @click="read">Read</button>
      <button type="button" @click="password.focus()">Focus</button>
    </div>
    <Field name="new-password">
      <FieldLabel>New password</FieldLabel>
      <PasswordInput :controller="password" auto-complete="new-password">
        <PasswordInputControl />
        <PasswordInputToggle v-slot="{ state }" aria-label="Show password">
          <EyeOffIcon v-if="state.visible" aria-hidden="true" />
          <EyeIcon v-else aria-hidden="true" />
        </PasswordInputToggle>
      </PasswordInput>
    </Field>
  </div>
</template>
选择 Suggest 填入并显示一个示例值。试试 Toggle、Read、Clear 和 Focus,从字段之外调用每个动作。

控制器介绍了如何创建和共享控制器。

表单

原生输入框参与 FormData、校验和重置。用 form 把它和页面别处的表单关联起来,就像这个示例一样。

控制台
<script setup lang="ts">
import { EyeIcon, EyeOffIcon } from "@lucide/vue"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import { Input } from "@ui-sdk/vue/input"
import {
  PasswordInput,
  PasswordInputControl,
  PasswordInputToggle,
} from "@ui-sdk/vue/password-input"
import { useLog } from "./log"

const log = useLog()

function onSubmit(event: Event) {
  const data = new FormData(event.currentTarget as HTMLFormElement)
  const length = String(data.get("password")).length
  log(
    `Signed in as ${data.get("email")}, with a password of ${length} characters`
  )
}
</script>

<template>
  <div data-slot="stack">
    <form id="sign-in" data-slot="stack" @submit.prevent="onSubmit">
      <Field name="email">
        <FieldLabel>Email</FieldLabel>
        <Input type="email" required autocomplete="username" />
      </Field>
    </form>
    <Field>
      <FieldLabel>Password</FieldLabel>
      <PasswordInput name="password" form="sign-in" required>
        <PasswordInputControl />
        <PasswordInputToggle v-slot="{ state }" aria-label="Show password">
          <EyeOffIcon v-if="state.visible" aria-hidden="true" />
          <EyeIcon v-else aria-hidden="true" />
        </PasswordInputToggle>
      </PasswordInput>
    </Field>
    <div data-slot="row">
      <button type="submit" form="sign-in" data-variant="solid">Sign In</button>
      <button type="reset" form="sign-in">Reset</button>
    </div>
  </div>
</template>
输入邮箱和密码,显示密码,然后在字段里按 Enter。提交会再次隐藏它,控制台会记录它的长度。重置会清空表单。为空的必填字段会阻止提交。

提交、重置和页面隐藏都会请求再次隐藏密码。重置还会恢复它的默认值。密码可见时,拼写标记、自动更正和自动大写保持禁用。

受控的值

用 v-model:value 绑定,或传入 value 并处理 @value-change。新密码示例就是这样推导检查清单的。状态与事件介绍了通用的状态约定。

<script setup lang="ts">
const password = ref("")
</script>

<template>
  <PasswordInput v-model:value="password">
    <PasswordInputControl aria-label="Password" />
    <PasswordInputToggle aria-label="Show password">Show</PasswordInputToggle>
  </PasswordInput>
</template>

自定义渲染

每个部件都接受一个 render 插槽,它收到要绑定的 props 和部件的状态;默认插槽也会收到状态:密码是否 visible、大写锁定是否开启(capsLock),以及字段是否 filled。渲染约定见部件与组合。

<PasswordInputToggle aria-label="Show password">
  <template #render="{ props, state }">
    <button v-bind="props">
      <EyeOffIcon v-if="state.visible" aria-hidden="true" />
      <EyeIcon v-else aria-hidden="true" />
    </button>
  </template>
</PasswordInputToggle>

样式

把根部件当作字段的盒子来设置样式,原生输入框和切换按钮放在里面。密码显示时,data-visible 会标记每个部件,切换按钮还会设置 aria-pressed。用 data-capslock 表示大写锁定警告,用 data-filled、data-disabled 和 data-readonly 表示字段的其他状态。在 Field 内部,原生输入框还会收到 data-invalid 这样的校验属性。使用逻辑间距,让字段和切换按钮跟随周围的方向。

每个部件都有一个 data-slot,比如 password-input-toggle,它的状态属性列在数据属性下。

数据属性

PasswordInput

[data-slot="password-input"]

属性含义
data-visiblePresent while the password is shown, so the field is a text field.
data-filledPresent while the field holds any text.
data-disabledPresent when disabled, by its own prop, a Field or a <fieldset>.
data-readonlyPresent when the field is read-only.
data-requiredPresent when a password is required.
data-capslockPresent while Caps Lock is on and the field has focus.

PasswordInputControl

[data-slot="password-input-control"]

属性含义
data-visiblePresent while the password is shown, so the field is a text field.
data-filledPresent while the field holds any text.
data-disabledPresent when disabled, by its own prop, a Field or a <fieldset>.
data-readonlyPresent when the field is read-only.
data-requiredPresent when a password is required.
data-capslockPresent while Caps Lock is on and the field has focus.

PasswordInputToggle

[data-slot="password-input-toggle"]

属性含义
data-visiblePresent while the password is shown, so the field is a text field.
data-filledPresent while the field holds any text.
data-disabledPresent when disabled, by its own prop, a Field or a <fieldset>.
data-readonlyPresent when the field is read-only.
data-requiredPresent when a password is required.
data-capslockPresent while Caps Lock is on and the field has focus.

API 参考

属性与下面相同,回调是事件。

PasswordInput

value?string
The value, for a controlled field.
defaultValue?string
The value it starts with. A form reset returns here.
@value-change((value: string, details: ChangeDetails<InputValueChangeReason>) => void)
Called when the user changes the value: typing ("input-change"), a Clear part ("clear-press"), a form reset ("reset") or a controller ("imperative"). details.cancel() keeps the value as it was.
visible?boolean
Whether the password is shown. Pass it to control it.
defaultVisible?boolean
Whether the password is shown at first, when uncontrolled.
@visible-change((visible: boolean, details: ChangeDetails<PasswordInputVisibleChangeReason>) => void)
Runs when the password wants to be shown or hidden: the toggle ("toggle-press"), submitting or resetting its form ("form-submit", "reset"), the page being hidden ("page-hide") or a controller ("imperative"). details.cancel() keeps it as it was; the field is a password field while the browser reads a submitted form either way.
autoComplete?"current-password" | "new-password" | "off" | (string & {})
What the browser and password managers fill in: "current-password" for signing in, "new-password" for signing up or changing it.
name?string
The name the password submits under. Inside a Field, the Field's name.
form?string
The id of the form the field belongs to, when it isn't inside it.
required?boolean
Whether a password is required to submit the form.
disabled?boolean
Disables the field and the toggle. Inside a Field or a disabled <fieldset>, they follow it.
readOnly?boolean
Makes the field read-only. The toggle still shows and hides it.
controller?object
Reads, writes, shows and hides it from anywhere. Create one with createPasswordInputController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

状态

渲染函数、基于状态的类名和槽位会收到什么。每个部件都会收到相同的状态。

visibleboolean
Whether the password is shown.
capsLockboolean
Whether Caps Lock is on while the field has focus.
filledboolean
Whether the field holds any text.
disabledboolean
Whether the field is disabled, by itself, its Field or a <fieldset>.
readOnlyboolean
Whether the field is read-only.
requiredboolean
Whether a form won't submit while the field is empty.

原因

details.reason 说明值为什么变更。自动填充和密码管理器的填入都是 input-change。

input-changeEvent
Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
clear-pressMouseEvent | KeyboardEvent
A Clear part was pressed, like on an input, a select or a combobox.
resetnone
A form reset.
imperativenone
A controller or api call.

以及密码为什么被显示或隐藏:

toggle-pressMouseEvent | KeyboardEvent
A toggle was pressed: a password input's, which shows or hides the password, or a carousel's, which starts or stops rotation.
form-submitSubmitEvent
The form was submitted, which hides a shown password so the browser offers to save it.
resetnone
A form reset.
page-hidePageTransitionEvent
The page was hidden, like when navigating away, which hides a shown password before the browser keeps the page.
imperativenone
A controller or api call.

控制器

用 createPasswordInputController() 创建一个,并作为 controller 传入。

每个写入方法都接受可选的 { reason, event },并像输入或按压一样运行变更回调。变更被取消时,setVisible() 和 toggleVisible() 返回 false。

getValue()() => string
The current value.
setValue(value, options?)(value: string, options?: ChangeOptions<InputValueChangeReason> | undefined) => boolean
Sets the value as if the user typed it, so input fires. Returns false when the change was canceled or nothing changed.
clear(options?)(options?: ChangeOptions<InputValueChangeReason> | undefined) => boolean
Empties the field, as if the user deleted the text, so input fires. Returns false when the change was canceled or nothing changed.
isVisible()() => boolean
Whether the password is shown.
setVisible(visible, options?)(visible: boolean, options?: ChangeOptions<PasswordInputVisibleChangeReason> | undefined) => boolean
Shows or hides the password. Returns false when canceled.
toggleVisible(options?)(options?: ChangeOptions<PasswordInputVisibleChangeReason> | undefined) => boolean
Shows the password if it's hidden, and hides it if it's shown. Returns false when canceled.
focus()() => void
Moves focus to the field.

事件

事件先收到新值,再收到详情。只有变更事件没有被取消时,v-model 才会更新。

绑定所属收到
v-model:valuePasswordInput密码
v-model:visiblePasswordInput密码是否显示
@value-changePasswordInput(value, details):新密码和原因
@visible-changePasswordInput(visible, details):密码是否要显示,以及原因

无障碍

密码字段没有 WAI-ARIA 模式。输入框保持为原生密码字段,由它的字段标签或 aria-label 提供名称;切换按钮则按 WAI-ARIA 按钮模式作为切换按钮。按切换按钮做的事来命名它,比如“Show password”,并保持这个名称不变:它的 aria-pressed 状态告诉屏幕阅读器密码是否显示,aria-controls 指向输入框。

键盘

Tab 从输入框移动到切换按钮,在切换按钮上按 Space 或 Enter 会显示或隐藏密码。在输入框里按 Enter 会提交它的表单;它永远不会按压切换按钮。

焦点

用指针按压切换按钮时,焦点留在输入框里,光标和选区保持原位。从别处按压会把焦点带回输入框。键盘按压会让焦点留在切换按钮上。

经过测试的行为

下面每一行都是一个自动化测试。

  • The field is a password field named by its label and described by its description.
  • The toggle is a button that says what it does, and isn't pressed.
  • Pressing the toggle shows the password, and pressing it again hides it.
  • Space on the focused toggle shows the password and keeps focus on the toggle.
  • Enter on the focused toggle shows the password and keeps focus on the toggle.
  • The toggle keeps its name when the password shows.
  • Enter in the field submits the form, and never presses the toggle.
  • The password submits under its name.
  • The password can start shown.
  • A change can be canceled.
  • A disabled password input disables the field and the toggle.
  • A read-only field can still be shown.
  • The controller shows and hides the password.
  • A controlled password input follows its owner. 仅在 React 和 Vue 运行。
  • A click with no pointer behind it, like a screen reader's, shows the password.

运行于 React、Vue 和 web components。

模式之外:

  • Showing the password keeps focus in the field, with the caret where it was.
  • Showing and hiding the password keeps the selection.
  • A click on the toggle while typing never blurs the field.
  • A click on the toggle from elsewhere brings focus back to the field.
  • Submitting hides a shown password before the page's own submit handler runs.
  • Submitting hides the password even when the change is canceled, while the browser reads the form.
  • Resetting the form hides the password.
  • Hiding the page hides the password, so the browser never keeps it as text.
  • A shown password is never spellchecked, autocorrected or capitalized.
  • The field asks password managers for the current password, or a new one.
  • Caps Lock marks the input while the field has focus.
  • A click into the field with Caps Lock on shows the warning before any key.
  • A web field keeps an autocomplete changed after it connects. 仅在 Web components 运行。
  • The toggle has its own id and controls the field.
  • A disabled fieldset disables the toggle too.

运行于 React、Vue 和 web components。

在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器录制:

  • Announcements while showing and hiding a password with a keyboard.

运行于 React、Vue 和 web components。

还测试了:

  • No axe violations at rest.
  • No axe violations with the password shown.
  • No axe violations while disabled.
  • No axe violations while read-only.
  • The field is named by its label, and the toggle by its aria-label.
  • Accessibility tree.

运行于 React、Vue 和 web components。