Blame view

src/components/StrengthMeter/index.tsx 2.06 KB
陈文彬 authored
1
2
3
4
5
6
7
8
9
import { PropType } from 'vue';

import { defineComponent, computed, ref, watch, unref, watchEffect } from 'vue';

import { Input } from 'ant-design-vue';

import zxcvbn from 'zxcvbn';
import { extendSlots } from '/@/utils/helper/tsxHelper';
import './index.less';
10
const prefixCls = 'strength-meter';
陈文彬 authored
11
export default defineComponent({
12
  name: 'StrengthMeter',
陈文彬 authored
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
  emits: ['score-change', 'change'],
  props: {
    value: {
      type: String as PropType<string>,
      default: undefined,
    },

    userInputs: {
      type: Array as PropType<string[]>,
      default: () => [],
    },

    showInput: {
      type: Boolean as PropType<boolean>,
      default: true,
    },
    disabled: {
      type: Boolean as PropType<boolean>,
      default: false,
    },
  },
  setup(props, { emit, attrs, slots }) {
    const innerValueRef = ref('');
    const getPasswordStrength = computed(() => {
      const { userInputs, disabled } = props;
      if (disabled) return null;
      const innerValue = unref(innerValueRef);
      const score = innerValue
        ? zxcvbn(unref(innerValueRef), (userInputs as string[]) || null).score
        : null;
      emit('score-change', score);
      return score;
    });

    function handleChange(e: ChangeEvent) {
      innerValueRef.value = e.target.value;
    }

    watchEffect(() => {
      innerValueRef.value = props.value || '';
    });
    watch(
      () => unref(innerValueRef),
      (val) => {
        emit('change', val);
      }
    );

    return () => {
      const { showInput, disabled } = props;
      return (
        <div class={prefixCls}>
          {showInput && (
            <Input.Password
              {...attrs}
              allowClear={true}
              value={unref(innerValueRef)}
              onChange={handleChange}
              disabled={disabled}
            >
              {extendSlots(slots)}
            </Input.Password>
          )}
          <div class={`${prefixCls}-bar`}>
            <div class={`${prefixCls}-bar__fill`} data-score={unref(getPasswordStrength)}></div>
          </div>
        </div>
      );
    };
  },
});