password-form.vue 1.92 KB
<script setup lang="ts">
  import { ref } from 'vue';
  import { Form, FormItem, InputPassword } from '@arco-design/web-vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';

  type formValueProp = {
    password: string;
    password_confirmation: string;
  };

  const props = defineProps<{ onRequest: (data: formValueProp) => Promise<void> }>();

  const formRef = ref<FormInstance>();
  const formValue = ref({ password: '', password_confirmation: '' });
  const rules = {
    password: [
      { required: true, message: '请输入新密码' },
      { minLength: 6, message: '新密码不能低于6位' },
      { maxLength: 20, message: '新的密码不能超过20位' },
    ],
    password_confirmation: [
      { required: true, message: '请输入确认密码' },
      { minLength: 6, message: '新密码不能低于6位' },
      { maxLength: 20, message: '新的密码不能超过20位' },
      {
        validator: (value: string | undefined, cb: (error?: string) => void) => {
          return new Promise((resolve) => {
            if (value !== formValue.value.password) {
              cb('确认密码与新密码不一致');
            }
            resolve(true);
          });
        },
      },
    ],
  };

  const onSubmit = async (): Promise<void> => {
    const error = await formRef.value?.validate();

    if (error) {
      return Promise.reject(error);
    }

    return props.onRequest(formValue.value);
  };

  defineExpose({ onSubmit });
</script>

<template>
  <Form ref="formRef" :model="formValue" :rules="rules" auto-label-width>
    <FormItem field="password" label="新密码">
      <InputPassword v-model="formValue.password" :max-length="20" />
    </FormItem>
    <FormItem field="password_confirmation" label="确认密码" row-class="mb-0">
      <InputPassword v-model="formValue.password_confirmation" :max-length="20" />
    </FormItem>
  </Form>
</template>

<style scoped lang="less"></style>