【山竹记账前端-vue】10.使用 Vant UI 制作数字按键


大纲链接 §

[toc]


1. 制作数字按键 ⇧

  • 声明按钮列表数据,遍历渲染;声明按钮类型
    • 按钮支持文字或图标
  • 使用二维布局 grid 做不规则分布的按钮
  • 四列四行,其中 清空(归零)、删除(图标)、提交、0 位数字占据跨多行/列
  • 父容器布局样式 grid grid-cols-[repeat(4,1fr)] grid-rows-[repeat(4,48px)]
  • 父容器设置背景色 #ddd,留出子节点空隙 gap-1px,设置子节点背景为白色,形成类似边框线条
  • 遍历的按钮对象需要设置具体不同的 grid-area-[],具体网格样式配置可参考:css grid generator

CSS Grid Generator Your Grid Code

@/modules/items/InputPad.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { defineComponent } from 'vue'
import { SvgIcon } from '@/components/icons/SvgIcon.tsx'
import { NumberOutput } from '@/modules/items/NumberOutput.tsx'
import type { SvgIconName } from '@svgoStore'
import { cn } from 'cn'

type ButtonItem<T extends boolean = boolean> = {
  text: string,
  onClick: () => void,
  gridArea: string,
} & (T extends true
  ? {
      hasIcon: T,
      iconName: SvgIconName,
    }
  : {
      hasIcon?: false,
      iconName?: never,
    })

export const InputPad = defineComponent({
  name: 'InputPad',
  setup(/* _props, _ctx */) {
    const buttons: ButtonItem[] = [
      {text: '1', onClick: () => {}, gridArea: 'grid-area-[1/1/2/2]',},
      {text: '2', onClick: () => {}, gridArea: 'grid-area-[1/2/2/3]',},
      {text: '3', onClick: () => {}, gridArea: 'grid-area-[1/3/2/4]',},
      {text: '清空', onClick: () => {}, gridArea: 'grid-area-[1/4/2/5]',},
      {text: '4', onClick: () => {}, gridArea: 'grid-area-[2/1/3/2]',},
      {text: '5', onClick: () => {}, gridArea: 'grid-area-[2/2/3/3]',},
      {text: '6', onClick: () => {}, gridArea: 'grid-area-[2/3/3/4]',},
      {text: '删除', onClick: () => {}, hasIcon: true, iconName: 'backspace', gridArea: 'grid-area-[2/4/3/5]',},
      {text: '7', onClick: () => {}, gridArea: 'grid-area-[3/1/4/2]',},
      {text: '8', onClick: () => {}, gridArea: 'grid-area-[3/2/4/3]',},
      {text: '9', onClick: () => {}, gridArea: 'grid-area-[3/3/4/4]',},
      {text: '提交', onClick: () => {}, gridArea: 'grid-area-[3/4/5/5]',},
      {text: '0', onClick: () => {}, gridArea: 'grid-area-[4/1/5/3]',},
      {text: '.', onClick: () => {}, gridArea: 'grid-area-[4/3/5/4]',},
    ]
    return () => (
      <>
        <div class="">
          <span class="notes">
            <SvgIcon name="date" />
            <span>2027-01-01</span>
          </span>
          <span class="amount">
            <NumberOutput />
          </span>
        </div>

        {/* 数字键盘 */}
        <div class={cn(
          'grid grid-cols-[repeat(4,1fr)] grid-rows-[repeat(4,48px)]',
          'bg-[#ddd] gap-1px p-1px',
          'children-bg-white children-b-none'
        )}>
          {buttons.map((buttonItem) => (
            <button
              type="button"
              key={buttonItem.text}
              onClick={buttonItem.onClick}
              class={cn(
                'flex justify-center items-center',
                buttonItem.gridArea,
              )}>
              {buttonItem.hasIcon ? <SvgIcon name={buttonItem.iconName} /> : buttonItem.text}
            </button>
          ))}
        </div>
      </>
    )
  },
})

2. 添加日期、金额结构样式 ⇧

@/modules/items/NumberOutput.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { defineComponent /* type PropType */ } from 'vue'

export const NumberOutput = defineComponent({
  name: 'NumberOutput',
  setup(/* _props, _ctx */) {
    return () => (
      <span class="text-24px font-mono color-[var(--amount-text-color)]">
        199.12
      </span>
    )
  },
})
  • 保证金额输出文字字体为等宽字体,添加样式 font-mono

@/modules/items/InputPad.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { defineComponent } from 'vue'
import { SvgIcon } from '@/components/icons/SvgIcon.tsx'
import { NumberOutput } from '@/modules/items/NumberOutput.tsx'
import type { SvgIconName } from '@svgoStore'
import { cn } from 'cn'

type ButtonItem<T extends boolean = boolean> = {
  text: string,
  onClick: () => void,
  gridArea: string,
  extraClass?: string,
} & (T extends true
  ? {
      hasIcon: T,
      iconName: SvgIconName,
    }
  : {
      hasIcon?: false,
      iconName?: never,
    })

export const InputPad = defineComponent({
  name: 'InputPad',
  setup(/* _props, _ctx */) {
    const buttons: ButtonItem[] = [
      {text: '1', onClick: () => {}, gridArea: 'grid-area-[1/1/2/2]',},
      {text: '2', onClick: () => {}, gridArea: 'grid-area-[1/2/2/3]',},
      {text: '3', onClick: () => {}, gridArea: 'grid-area-[1/3/2/4]',},
      {text: '清空', onClick: () => {}, gridArea: 'grid-area-[1/4/2/5]',},
      {text: '4', onClick: () => {}, gridArea: 'grid-area-[2/1/3/2]',},
      {text: '5', onClick: () => {}, gridArea: 'grid-area-[2/2/3/3]',},
      {text: '6', onClick: () => {}, gridArea: 'grid-area-[2/3/3/4]',},
      {text: '删除', onClick: () => {}, hasIcon: true, iconName: 'backspace',
        gridArea: 'grid-area-[2/4/3/5]', extraClass: cn('children:w-1.5em children:h-1.5em'),},
      {text: '7', onClick: () => {}, gridArea: 'grid-area-[3/1/4/2]',},
      {text: '8', onClick: () => {}, gridArea: 'grid-area-[3/2/4/3]',},
      {text: '9', onClick: () => {}, gridArea: 'grid-area-[3/3/4/4]',},
      {text: '提交', onClick: () => {}, gridArea: 'grid-area-[3/4/5/5]',},
      {text: '0', onClick: () => {}, gridArea: 'grid-area-[4/1/5/3]',},
      {text: '.', onClick: () => {}, gridArea: 'grid-area-[4/3/5/4]',},
    ]
    const numberSizeClass = (text: string) => (/[0-9.]/g).test(text)
      ? cn('text-18px')
      : ''
    return () => (
      <>
        {/* 日期、金额输入 */}
        <div class="flex justify-between items-center py-1em b-t-[var(--button-border-color)] b-t-1">
          <span class="flex justify-start items-center">
            <SvgIcon name="date" class="size-2em mx-1 fill-[var(--button-bg)]" />
            <span class="text-14px font-mono animation-rainbow color-[var(--vp-c-brand-next)]">2027-01-01</span>
          </span>

          <NumberOutput class="mr-4" />
        </div>
        {/* 数字键盘 */}
        <div class={cn(
          'grid grid-cols-[repeat(4,1fr)] grid-rows-[repeat(4,56px)]',
          'bg-[var(--button-border-color)] gap-1px p-y-1px',
          'children-bg-white children-b-none'
        )}>
          {buttons.map((buttonItem) => (
            <button
              type="button"
              key={buttonItem.text}
              onClick={buttonItem.onClick}
              class={cn(
                'flex justify-center items-center font-bold',
                buttonItem.gridArea,
                buttonItem?.extraClass,
                numberSizeClass(buttonItem.text),
              )}>
              {buttonItem.hasIcon ? <SvgIcon name={buttonItem.iconName} /> : buttonItem.text}
            </button>
          ))}
        </div>
      </>
    )
  },
})

拆分 @/modules/items/Numpad.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { defineComponent /* type PropType */ } from 'vue'
import { cn } from 'cn'
import { SvgIcon } from '@/components/icons/SvgIcon.tsx'
import type { SvgIconName } from '@svgoStore'

type ButtonItem<T extends boolean = boolean> = {
  text: string,
  onClick: () => void,
  gridArea: string,
  extraClass?: string,
} & (T extends true
  ? {
    hasIcon: T,
    iconName: SvgIconName,
  }
  : {
    hasIcon?: false,
    iconName?: never,
  })

export const Numpad = defineComponent({
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Numpad',
  setup(/* _props, _ctx */) {
    const buttons: ButtonItem[] = [
      {text: '1', onClick: () => {}, gridArea: 'grid-area-[1/1/2/2]',},
      {text: '2', onClick: () => {}, gridArea: 'grid-area-[1/2/2/3]',},
      {text: '3', onClick: () => {}, gridArea: 'grid-area-[1/3/2/4]',},
      {text: '清空', onClick: () => {}, gridArea: 'grid-area-[1/4/2/5]',},
      {text: '4', onClick: () => {}, gridArea: 'grid-area-[2/1/3/2]',},
      {text: '5', onClick: () => {}, gridArea: 'grid-area-[2/2/3/3]',},
      {text: '6', onClick: () => {}, gridArea: 'grid-area-[2/3/3/4]',},
      {text: '删除', onClick: () => {}, hasIcon: true, iconName: 'backspace',
        gridArea: 'grid-area-[2/4/3/5]', extraClass: cn('children:w-1.5em children:h-1.5em'),},
      {text: '7', onClick: () => {}, gridArea: 'grid-area-[3/1/4/2]',},
      {text: '8', onClick: () => {}, gridArea: 'grid-area-[3/2/4/3]',},
      {text: '9', onClick: () => {}, gridArea: 'grid-area-[3/3/4/4]',},
      {text: '提交', onClick: () => {}, gridArea: 'grid-area-[3/4/5/5]',},
      {text: '0', onClick: () => {}, gridArea: 'grid-area-[4/1/5/3]',},
      {text: '.', onClick: () => {}, gridArea: 'grid-area-[4/3/5/4]',},
    ]
    const numberSizeClass = (text: string) => (/[0-9.]/g).test(text)
      ? cn('text-18px')
      : ''
    return () => (
      <div class={cn(
        'grid grid-cols-[repeat(4,1fr)] grid-rows-[repeat(4,56px)]',
        'bg-[var(--button-border-color)] gap-1px p-y-1px',
        'children-bg-white children-b-none'
      )}>
        {buttons.map((buttonItem) => (
          <button
            type="button"
            key={buttonItem.text}
            onClick={buttonItem.onClick}
            class={cn(
              'flex justify-center items-center font-bold',
              buttonItem.gridArea,
              buttonItem?.extraClass,
              numberSizeClass(buttonItem.text),
            )}>
            {buttonItem.hasIcon ? <SvgIcon name={buttonItem.iconName} /> : buttonItem.text}
          </button>
        ))}
      </div>
    )
  },
})

3. 封装 time.tsx ⇧

@src/shared/time.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
export const time = (date?: Date) => {
  if(!date) {date = new Date()}
  // 目前支持的格式有 'YYYY-MM-DD HH:mm:ss.sss'
  const api = {
    format: (pattern: string = 'YYYY-MM-DD') => {
      // YYYY
      const year = date.getFullYear()
      // MM
      const month = date.getMonth() + 1
      // DD
      const day = date.getDate()
      // HH
      const hour = date.getHours()
      // mm
      const minute = date.getMinutes()
      // ss
      const second = date.getSeconds()
      // sss
      const millisecond = date.getMilliseconds()

      return pattern
        .replace(/YYYY/g, year.toString())
        // 使用 padStart 长度不足则补零
        .replace(/MM/g, month.toString().padStart(2, '0'))
        .replace(/DD/g, day.toString().padStart(2, '0'))
        .replace(/HH/g, hour.toString().padStart(2, '0'))
        .replace(/mm/g, minute.toString().padStart(2, '0'))
        .replace(/ss/g, second.toString().padStart(2, '0'))
        .replace(/sss/g, millisecond.toString().padStart(3, '0'))
    }
  }

  return {
    api,
  }
}

使用 @/modules/items/InputPad.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { defineComponent } from 'vue'
import { SvgIcon } from '@/components/icons/SvgIcon.tsx'
import { NumberOutput } from '@/modules/items/NumberOutput.tsx'
import { Numpad } from '@/modules/items/Numpad.tsx'
import { time } from '@/shared/time.ts'

export const InputPad = defineComponent({
  name: 'InputPad',
  setup(/* _props, _ctx */) {
    const now = new Date()
    const {api: dateApi} = time(now)

    return () => (
      <>
        {/* 日期、金额输入 */}
        <div class="flex justify-between items-center py-1em b-t-[var(--button-border-color)] b-t-1">
          <span class="flex justify-start items-center">
            <SvgIcon name="date" class="size-2em mx-1 fill-[var(--button-bg)]" />
            <span class="animation-rainbow text-14px font-mono color-[var(--vp-c-brand-next)]">
              <input type="date" value={dateApi.format()} />
            </span>
          </span>

          <NumberOutput class="mr-4" />
        </div>

        {/* 数字键盘 */}
        <Numpad />
      </>
    )
  },
})

4. 使用 Vant UI 制作日期组件 ⇧

安装、配置、引入样式 ⇧

安装 Vant 4,按需引入组件样式,并安装 unplugin-vue-components

1
2
pnpm add vant@4.10.2
pnpm add -D unplugin-vue-components@32.1.0 @vant/auto-import-resolver@1.3.0 unplugin-auto-import@21.1.0

配置 vite.config.ts,并配置自动组件导入插件(类型)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { fileURLToPath, pathToFileURL, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import unoCSS from 'unocss/vite'
import jsxScoped from '@10coding/vite-plugin-jsx-scoped'
import { svgoStore } from './src/plugins/svgoStore.ts'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'

// https://vite.dev/config/
export default defineConfig({
  // base: '/mangosteen-fe-0-publish/',
  plugins: [
    unoCSS(),
    jsxScoped({ warnMultiScopedImport: true }),
    vue(),
    vueJsx({
      transformOn: true,
      mergeProps: true,
    }),
    AutoImport({
      resolvers: [
        VantResolver(),
      ],
    }),
    Components({
      resolvers: [
        VantResolver(),
      ],
    }),
    vueDevTools(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        // 自定义 importers 解析 @/ 别名
        importers: [
          {
            findFileUrl(url) {
              if (!url.startsWith('@/')) return null;
              return new URL(url.substring(2), pathToFileURL('./src'));
            }
          },
        ],
      },
    },
  },
})

引入样式 @/main.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from '@/router'
import { App } from '@/App.tsx'
import '@/assets/styles/main.scss'
import '@svgoStore'
// vendors
import 'uno.css'
// import 'virtual:uno.css'
import 'vant/lib/index.css'

const app = createApp(App)

app.use(createPinia())
app.use(router)

app.mount('#app')

弹出层组件配合实现日期组件 ⇧

替换掉原生日期输入框,@/modules/items/InputPad.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { computed, defineComponent, ref } from 'vue'
import { SvgIcon } from '@/components/icons/SvgIcon.tsx'
import { NumberOutput } from '@/modules/items/NumberOutput.tsx'
import { Numpad } from '@/modules/items/Numpad.tsx'
import { time } from '@/shared/time.ts'
import { DatePicker, Popup } from 'vant'

export const InputPad = defineComponent({
  name: 'InputPad',
  setup(/* _props, _ctx */) {
    const datePickerVisibleRef = ref(false)
    const lastDateRef = ref(['2026', '11', '01'])
    const currentDateRef = ref(['2026', '11', '01'])
    const minDate = new Date(2025, 1, 1)
    const maxDate = new Date(2028, 0, 1)
    const formattedDateStr = computed(() =>
      time(new Date(currentDateRef.value.join('-'))).api.format(),
    )
    const toggleDatePicker = () => {
      datePickerVisibleRef.value = !datePickerVisibleRef.value
    }
    const confirmDate = ({ selectedValues }: {selectedValues: string[]}) => {
      lastDateRef.value = selectedValues
      currentDateRef.value = selectedValues
      datePickerVisibleRef.value = false
    }
    const cancelDate = () => {
      currentDateRef.value = lastDateRef.value
      datePickerVisibleRef.value = false
    }

    return () => (
      <>
        {/* 日期、金额输入 */}
        <div class="flex justify-between items-center py-1em b-t-[var(--button-border-color)] b-t-1">
          <span class="flex justify-start items-center">
            <SvgIcon name="date" class="size-2em mx-1 fill-[var(--button-bg)]" />
            <span class="animation-rainbow text-14px font-mono color-[var(--vp-c-brand-next)]">
              <span onClick={toggleDatePicker}>{formattedDateStr.value}</span>
              <Popup
                position="bottom"
                v-model:show={datePickerVisibleRef.value}
                onClose={cancelDate}>
                <DatePicker
                  title="选择年月日"
                  v-model={currentDateRef.value}
                  minDate={minDate}
                  maxDate={maxDate}
                  onConfirm={confirmDate}
                  onCancel={cancelDate}/>
              </Popup>
            </span>
          </span>

          <NumberOutput class="mr-4" />
        </div>

        {/* 数字键盘 */}
        <Numpad />
      </>
    )
  },
})
  • datePickerVisibleRef 控制 Popup 显示状态
  • lastDateRef 为 DatePicker 暂存上一次选择数据,用来取消时,恢复上一次数据
  • currentDateRef 为 DatePicker 当前选择数据
  • DatePicker 设置范围 minDate、maxDate,格式为 new Date(2028, 0, 1)
  • formattedDateStr 配合自己封装的 time 函数,计算格式化后的字符串
  • toggleDatePicker 切换开/关 Popup
  • confirmDate 确认选择日期,同时更新 lastDateRef 和 currentDateRef
  • cancelDate 取消选择日期,由于切换日期时组件立即就会同时更新 currentDateRef 数据,取消时需要恢复上一次选择的数据 lastDateRef

拆分弹出层日期组件,重构组件 ⇧

重构重命名 NumberOutput.tsx 为 AmountNumberOutput

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { defineComponent, ref } from 'vue'

export const AmountNumberOutput = defineComponent({
  name: 'AmountNumberOutput',
  setup(/* _props, _ctx */) {
    const amountRef = ref('99.09')
    return () => (
      <span class="text-24px font-mono color-[var(--amount-text-color)]">
        {amountRef.value}
      </span>
    )
  },
})

拆分为日期输入组件 @/modules/items/DateInput.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { computed, defineComponent, ref } from 'vue'
import { SvgIcon } from '@/components/icons/SvgIcon.tsx'
import { DatePicker, Popup } from 'vant'
import { time } from '@/shared/time.ts'

export const DateInput = defineComponent({
  name: 'DateInput',
  setup(/* _props, _ctx */) {
    const datePickerVisibleRef = ref(false)
    const lastDateRef = ref(['2026', '11', '01'])
    const currentDateRef = ref(['2026', '11', '01'])
    const minDate = new Date(2025, 1, 1)
    const maxDate = new Date(2028, 0, 1)
    const formattedDateStr = computed(() =>
      time(new Date(currentDateRef.value.join('-'))).api.format(),
    )
    const toggleDatePicker = () => {
      datePickerVisibleRef.value = !datePickerVisibleRef.value
    }
    const confirmDate = ({ selectedValues }: {selectedValues: string[]}) => {
      lastDateRef.value = selectedValues
      currentDateRef.value = selectedValues
      datePickerVisibleRef.value = false
    }
    const cancelDate = () => {
      currentDateRef.value = lastDateRef.value
      datePickerVisibleRef.value = false
    }

    return () => (
      <span class="flex justify-start items-center">
        <SvgIcon onClick={toggleDatePicker} name="date" class="size-2em mx-1 fill-[var(--button-bg)]" />
        <span class="animation-rainbow text-14px font-mono color-[var(--vp-c-brand-next)]">
          <span onClick={toggleDatePicker}>{formattedDateStr.value}</span>
          <Popup
            position="bottom"
            v-model:show={datePickerVisibleRef.value}
            onClose={cancelDate}>
            <DatePicker
              title="选择年月日"
              v-model={currentDateRef.value}
              minDate={minDate}
              maxDate={maxDate}
              onConfirm={confirmDate}
              onCancel={cancelDate}/>
          </Popup>
        </span>
      </span>
    )
  },
})

原输入键盘组件简化 @/modules/items/InputPad.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import { defineComponent } from 'vue'
import { AmountNumberOutput } from '@/modules/items/AmountNumberOutput.tsx'
import { Numpad } from '@/modules/items/Numpad.tsx'
import { DateInput } from '@/modules/items/DateInput.tsx'

export const InputPad = defineComponent({
  name: 'InputPad',
  setup(/* _props, _ctx */) {
    return () => (
      <>
        {/* 日期输入、金额显示 */}
        <div class="flex justify-between items-center py-1em b-t-[var(--button-border-color)] b-t-1">
          <DateInput />
          <AmountNumberOutput class="mr-4" />
        </div>
        {/* 数字键盘 */}
        <Numpad />
      </>
    )
  },
})

5. 砍需求啦!对比使用 unocss 内联样式 和 CSS Module 集中管理 grid 布局 ⇧

对比原代码中的 InputPad.module.scss 键盘部分样式,使用 CSS Module 修改数字键盘组件样式 @/modules/items/Numpad.module.scss

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
// 定义所有 grid-area 的名称列表,名称不能以纯数字开头、不能包含符号(例如 .)
// 与tsx名称逻辑耦合,两边一致
$btn-names: (
  btn_1, btn_2, btn_3, btn_清空,
  btn_4, btn_5, btn_6, btn_删除,
  btn_7, btn_8, btn_9, btn_提交,
  btn_0, btn_dot,
);

.button-wrapper {
  display: grid;
  grid-template-areas:
    "btn_1 btn_2 btn_3 btn_清空"
    "btn_4 btn_5 btn_6 btn_删除"
    "btn_7 btn_8 btn_9 btn_提交"
    "btn_0 btn_0 btn_dot btn_提交";
  grid-auto-rows: 56px;
  grid-auto-columns: 1fr;
  background: var(--pad-border-color);
  gap: 1px;
  border-top: 1px solid var(--pad-border-color);

  & > .button-item {
    border: unset;
    background: var(--pad-button-bg-color);

    // 遍历生成对应的 grid-area 样式
    @each $name in $btn-names {
      &[data-btn-text="#{$name}"] {
        grid-area: $name;
      }
    }

    &[data-btn-text="btn_删除"] :nth-child(n) {
      width: 1.5em;
      height: 1.5em;
    }

    &[data-btn-text="btn_dot"] :nth-child(n) {
      width: 2em;
      height: 2em;
      transform: translateY(-5px);
      font-weight: bolder;
    }

    &[data-btn-text="btn_提交"] {
      background-color: var(--pad-submit-button-bg-color);
      color: var(--pad-submit-button-text-color);
    }
  }
}
  • 定义 grid-area 的名称列表;遍历生成对应的 grid-area 子元素样式名称
  • 与tsx名称逻辑强耦合
  • 样式集中管理,而不是像 tsx 中使用 unocss 可能样式分散在不同逻辑中
  • CSS Module 中的 grid-template-areas 写法更直观

@/modules/items/Numpad.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
// import ...
import s from '@/modules/items/Numpad.module.scss'

// type ButtonItem<T extends boolean = boolean> = ...

export const Numpad = defineComponent({
  name: 'Numpad',
  setup(/* _props, _ctx */) {
    const buttons: ButtonItem[] = [
      {text: '1', onClick: () => {},},
      {text: '2', onClick: () => {},},
      {text: '3', onClick: () => {},},
      {text: '清空', onClick: () => {},},
      {text: '4', onClick: () => {},},
      {text: '5', onClick: () => {},},
      {text: '6', onClick: () => {},},
      {
        text: '删除',
        onClick: () => {},
        hasIcon: true,
        iconName: 'backspace',
        extraClass: cn('children:w-1.5em children:h-1.5em'),
      },
      {text: '7', onClick: () => {},},
      {text: '8', onClick: () => {},},
      {text: '9', onClick: () => {},},
      {
        text: '提交',
        onClick: () => {},
        extraClass: cn('bg-[var(--pad-submit-button-bg-color)] text-[var(--button-text-color)]'),
      },
      {text: '0', onClick: () => {},},
      {
        text: 'dot', 
        onClick: () => {},
        hasIcon: true, 
        iconName: 'decimal_point', 
        extraClass: cn('children:(w-2em h-2em translate-y-[-9px] font-extrabold)'),
      },
    ]
    return () => (
      <div class={s['button-wrapper']}>
        {buttons.map((buttonItem) => (
          <button
            type="button"
            key={buttonItem.text}
            data-btn-text={buttonItem.text}
            onClick={buttonItem.onClick}
            class={s['button-item']}>
            {buttonItem.hasIcon ? <SvgIcon name={buttonItem.iconName} /> : buttonItem.text}
          </button>
        ))}
      </div>
    )
  },
})
  • 在每个button上动态生成 data-btn-text={buttonItem.text} 属性,以便在 CSS Module 中获取属性选择器
  • CSS Module 中遍历生成对应的 grid-area 样式,也可以直接写到元素中 style={{'grid-area': `btn_${buttonItem.text}`}}

    • 在父元素中使用 style 来写 grid-template-areas,命名更直观

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      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
      
      // ...
      export const Numpad = defineComponent({
      // eslint-disable-next-line vue/multi-word-component-names
      name: 'Numpad',
      setup(/* _props, _ctx */) {
      const buttons: ButtonItem[] = [
      {text: '1', onClick: () => {},},
      {text: '2', onClick: () => {},},
      {text: '3', onClick: () => {},},
      {text: '清空', onClick: () => {},},
      {text: '4', onClick: () => {},},
      {text: '5', onClick: () => {},},
      {text: '6', onClick: () => {},},
      {text: '删除', onClick: () => {}, hasIcon: true, iconName: 'backspace',
      extraClass: cn('children:w-1.5em children:h-1.5em'),},
      {text: '7', onClick: () => {},},
      {text: '8', onClick: () => {},},
      {text: '9', onClick: () => {},},
      {text: '提交', onClick: () => {},
      extraClass: cn('bg-[var(--pad-submit-button-bg-color)] text-[var(--button-text-color)]'),},
      {text: '0', onClick: () => {},},
      {text: 'dot', onClick: () => {},
      hasIcon: true, iconName: 'decimal_point', extraClass: cn('children:(w-2em h-2em translate-y-[-9px] font-extrabold)'),},
      ]
      const numberSizeClass = (text: string) => (/[0-9.]/g).test(text)
      ? cn('text-18px')
      : ''
      return () => (
      <div
      class={cn(
        s['button-wrapper'],
      )}
      style={{
        'grid-template-areas': `
        'btn_1 btn_2 btn_3 btn_清空'
        'btn_4 btn_5 btn_6 btn_删除'
        'btn_7 btn_8 btn_9 btn_提交'
        'btn_0 btn_0 btn_dot btn_提交'
        `
      }}>
      {buttons.map((buttonItem) => (
        <button
          type="button"
          key={buttonItem.text}
          data-btn-text={`btn_${buttonItem.text}`}
          onClick={buttonItem.onClick}
          style={{
            'grid-area': `btn_${buttonItem.text}`,
          }}
          class={cn(
            numberSizeClass(buttonItem.text),
            s['button-item'],
          )}>
          {buttonItem.hasIcon ? <SvgIcon name={buttonItem.iconName} /> : buttonItem.text}
        </button>
      ))}
      </div>
      )
      },
      })
      

@/modules/items/Numpad.module.scss 中相应的样式可简化为

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
.button-wrapper {
  display: grid;
  grid-auto-rows: 56px;
  grid-auto-columns: 1fr;
  background: var(--pad-border-color);
  gap: 1px;
  border-top: 1px solid var(--pad-border-color);

  & > .button-item {
    border: unset;
    background: var(--pad-button-bg-color);
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: bolder;

    /* 与tsx中名称逻辑耦合,两边一致 */
    &[data-btn-text="btn_删除"] :nth-child(n) {
      width: 1.5em;
      height: 1.5em;
    }

    &[data-btn-text="btn_dot"] :nth-child(n) {
      width: 2em;
      height: 2em;
      transform: translateY(-5px);
      font-weight: bolder;
    }

    &[data-btn-text="btn_提交"] {
      background-color: var(--pad-submit-button-bg-color);
      color: var(--pad-submit-button-text-color);
    }

  }
}

对比使用 unocss 的 @/modules/items/Numpad.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { defineComponent, } from 'vue'
import { cn } from 'cn'
import { SvgIcon } from '@/components/icons/SvgIcon.tsx'
import type { SvgIconName } from '@svgoStore'
import { useNumpadAmountStore } from '@/stores/useNumpadAmountStore.ts'
// import s from '@/modules/items/Numpad.module.scss'

type ButtonItem<T extends boolean = boolean> = {
  text: string,
  onClick: () => void,
  gridArea: string,
  extraClass?: string,
} & (T extends true
  ? {
    hasIcon: T,
    iconName: SvgIconName,
  }
  : {
    hasIcon?: false,
    iconName?: never,
  })

export const Numpad = defineComponent({
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Numpad',
  setup(/* _props, _ctx */) {
    const {appendText} = useNumpadAmountStore()
    const buttons: ButtonItem[] = [
      {text: '1', onClick: () => {appendText('1')}, gridArea: 'grid-area-[1/1/2/2]',},
      {text: '2', onClick: () => {appendText('2')}, gridArea: 'grid-area-[1/2/2/3]',},
      {text: '3', onClick: () => {appendText('3')}, gridArea: 'grid-area-[1/3/2/4]',},
      {text: '清空', onClick: () => {}, gridArea: 'grid-area-[1/4/2/5]',},
      {text: '4', onClick: () => {appendText('4')}, gridArea: 'grid-area-[2/1/3/2]',},
      {text: '5', onClick: () => {}, gridArea: 'grid-area-[2/2/3/3]',},
      {text: '6', onClick: () => {}, gridArea: 'grid-area-[2/3/3/4]',},
      {text: '删除', onClick: () => {}, hasIcon: true, iconName: 'backspace',
        gridArea: 'grid-area-[2/4/3/5]', extraClass: cn('children:w-1.5em children:h-1.5em'),},
      {text: '7', onClick: () => {}, gridArea: 'grid-area-[3/1/4/2]',},
      {text: '8', onClick: () => {}, gridArea: 'grid-area-[3/2/4/3]',},
      {text: '9', onClick: () => {}, gridArea: 'grid-area-[3/3/4/4]',},
      {text: '提交', onClick: () => {}, gridArea: 'grid-area-[3/4/5/5]',
        extraClass: cn('bg-[var(--pad-submit-button-bg-color)] text-[var(--button-text-color)]'),},
      {text: '0', onClick: () => {appendText('0')}, gridArea: 'grid-area-[4/1/5/3]',},
      {text: 'dot', onClick: () => {appendText('.')}, gridArea: 'grid-area-[4/3/5/4]',
        hasIcon: true, iconName: 'decimal_point', extraClass: cn('children:(w-2em h-2em translate-y-[-9px] font-extrabold)'),},
    ]
    const numberSizeClass = (text: string) => (/[0-9.]/g).test(text)
      ? cn('text-18px')
      : ''
    return () => (
      <div class={cn(
        'button-wrapper grid grid-cols-[repeat(4,1fr)] grid-rows-[repeat(4,56px)]',
        'bg-[var(--pad-border-color)] gap-1px p-t-1px',
        // s['button-wrapper'],
      )}>
        {buttons.map((buttonItem) => (
          <button
            type="button"
            key={buttonItem.text}
            data-btn-text={`btn_${buttonItem.text}`}
            onClick={buttonItem.onClick}
            class={cn(
              'buttonItem flex justify-center items-center font-bold',
              'bg-white b-unset',
              buttonItem.gridArea,
              buttonItem?.extraClass,
              numberSizeClass(buttonItem.text),
              // s['button-item'],
            )}>
            {buttonItem.hasIcon ? <SvgIcon name={buttonItem.iconName} /> : buttonItem.text}
          </button>
        ))}
      </div>
    )
  },
})
  • 布局样式都分散在每项数据的属性 grid-area-[x/x/x] 中,写起来并不直观
  • 使用 grid-template-areas 命名网格区域更直观

6. 数字输入检查 ⇧

使用 pinia 状态解耦键盘输入判断操作逻辑与金额状态 ⇧

使用 @/stores/useNumpadAmountStore.ts 解耦键盘输入判断操作逻辑与金额状态

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { showNotify } from 'vant'

export const useNumpadAmountStore = defineStore('numpadAmount', () => {
  const amountRef = ref('0.00')

  const appendText = (inputText: string) => {
    amountRef.value += inputText
  }

  const clearText = () => { amountRef.value = '0.00' }

  const backspaceText = () => {
    amountRef.value = amountRef.value.slice(0, -1)
    // 删空则补零
    if(amountRef.value === '') { amountRef.value = '0'}
  }

  return {
    amountRef,
    appendText,
    clearText,
    backspaceText,
  }
})
  • 金额状态 amountRef
  • 输入追加字符 appendText
  • 归零 clearText
  • 退格 backspaceText
  • 之后完善逻辑

应用到 @/modules/items/Numpad.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
// import ...

type ButtonItem<T extends boolean = boolean> = {/* ... */}

export const Numpad = defineComponent({
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Numpad',
  setup(/* _props, _ctx */) {
    const {
      appendText,
      clearText,
      backspaceText,
    } = useNumpadAmountStore()
    const buttons: ButtonItem[] = [
      {id: '1', text: '1', onClick: () => {appendText('1')},},
      {id: '2', text: '2', onClick: () => {appendText('2')},},
      {id: '3', text: '3', onClick: () => {appendText('3')},},
      {id: 'clear', text: Math.random() > .5 ? '归零' : '清空', onClick: () => {clearText()},},
      {id: '4', text: '4', onClick: () => {appendText('4')}, },
      {id: '5', text: '5', onClick: () => {appendText('5')}, },
      {id: '6', text: '6', onClick: () => {appendText('6')}, },
      {id: 'backspace', text: '退格', onClick: () => {backspaceText()}, hasIcon: true, iconName: 'backspace',
        extraClass: cn('children:(size-1.5em)'),},
      {id: '7', text: '7', onClick: () => {appendText('7')}, },
      {id: '8', text: '8', onClick: () => {appendText('8')},},
      {id: '9', text: '9', onClick: () => {appendText('9')}, },
      {id: 'submit', text: '提交', onClick: () => {clearText()},
        extraClass: cn('bg-[var(--pad-submit-button-bg-color)] text-[var(--button-text-color)]'),},
      {id: '0', text: '0', onClick: () => {appendText('0')}, },
      {id: 'dot', text: 'dot', onClick: () => {appendText('.')},
        hasIcon: true, iconName: 'decimal_point',
        extraClass: cn('children:(size-2em translate-y-[-9px] font-extrabold)'),},
    ]
    const numberSizeClass = (text: string) => (/[0-9|dot]/g).test(text)
      ? cn('text-18px')
      : ''
    return () => (
      <div
        class={cn(
        'grid grid-cols-[repeat(4,1fr)] grid-rows-[repeat(4,56px)]',
        'bg-[var(--pad-border-color)] gap-1px p-t-1px',
        s['button-wrapper'],
        )}
        style={{
          'grid-template-areas': `
          'btn_1 btn_2 btn_3 btn_clear'
          'btn_4 btn_5 btn_6 btn_backspace'
          'btn_7 btn_8 btn_9 btn_submit'
          'btn_0 btn_0 btn_dot btn_submit'
          `
        }}>
        {buttons.map((buttonItem) => (
          <button
            type="button"
            key={buttonItem.text}
            data-btn-text={`btn_${buttonItem.id}`}
            onClick={buttonItem.onClick}
            style={{
              'grid-area': `btn_${buttonItem.id}`,
            }}
            class={cn(
              'flex justify-center items-center font-bold',
              'bg-[var(--pad-button-bg-color)] b-unset',
              buttonItem?.extraClass,
              numberSizeClass(buttonItem.text),
              s['button-item'],
            )}>
            {buttonItem.hasIcon ? <SvgIcon name={buttonItem.iconName} /> : buttonItem.text}
          </button>
        ))}
      </div>
    )
  },
})

应用到 @/modules/items/AmountNumberOutput.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import { defineComponent, } from 'vue'
import { storeToRefs } from 'pinia'
import { useNumpadAmountStore } from '@/stores/useNumpadAmountStore.ts'

export const AmountNumberOutput = defineComponent({
  name: 'AmountNumberOutput',
  setup(/* _props, _ctx */) {
    const { amountRef } = storeToRefs(useNumpadAmountStore())
    return () => (
      <span class="text-24px font-mono color-[var(--amount-text-color)]">
        {amountRef.value}
      </span>
    )
  },
})

完善解耦键盘输入判断操作逻辑 ⇧

使用 if 判断 @/stores/useNumpadAmountStore.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { showNotify } from 'vant'

export const useNumpadAmountStore = defineStore('numpadAmount', () => {
  const amountRef = ref('0.00')

  const appendText = (inputText: string) => {
    // 如果当前金额为'0.00',则清空金额
    if(amountRef.value === '0.00') { amountRef.value = ''}
    // 小数点后已经有两位数字,则不能再输入
    if(amountRef.value.match(/\.\d{2}/)) {inputText = ''}
    // 已经有'.',则不能再输入'.'
    if(amountRef.value.match(/\./) && inputText === '.') {inputText = ''}
    // 输入'.',判断当前金额是否为空,是则首位补零
    if(inputText === '.' && amountRef.value === '') {
      amountRef.value = '0'
    }
    // 输入 '0',判断金额是否为'0',是则不输入
    if(amountRef.value === '0' && inputText === '0') {
      inputText = ''
    }
    // 输入 '1' ~' 9'.判断金额是否为'0',是则替换为1~9
    if((/[1-9]/g).test(inputText) && amountRef.value === '0') {
      amountRef.value = inputText
      inputText = ''
    }
    // 位数超过10位数字,则不能再输入,并提示
    if((amountRef.value).replace('.', '').length > 10) {
      showNotify({ type: 'warning', position: 'bottom', message: '输入的位数不支持超过10位', })
      inputText = ''
    }
    amountRef.value += inputText
  }

  const clearText = () => { amountRef.value = '0.00' }

  const backspaceText = () => {
    amountRef.value = amountRef.value.slice(0, -1)
    // 删空则补零
    if(amountRef.value === '') { amountRef.value = '0'}
  }

  return {
    amountRef,
    appendText,
    clearText,
    backspaceText,
  }
})

复杂度太高,改用条件数组模式表驱动重构 @/stores/useNumpadAmountStore.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { showNotify } from 'vant'

export const useNumpadAmountStore = defineStore('numpadAmount', () => {
  const amountRef = ref('0.00')

  const appendText = (inputText: string) => {
    const conditions = [
      {
        ruleHint: `输入时,如果当前金额为'0.00',则清空金额`,
        check: () => amountRef.value === '0.00',
        action: () => { amountRef.value = '' },
      },
      {
        ruleHint: `小数点后已经有两位数字,则不能再输入`,
        check: () => (/\.\d{2}/).test(amountRef.value),
        action: () => { inputText = '' },
      },
      {
        ruleHint: `已经有'.',则不能再输入'.'`,
        check: () => amountRef.value.includes('.') && inputText === '.',
        action: () => { inputText = '' },
      },
      {
        ruleHint: `输入'.',判断当前金额是否为空,是则首位补零`,
        check: () => inputText === '.' && amountRef.value === '',
        action: () => {amountRef.value = '0'},
      },
      {
        ruleHint: `输入 '0',判断金额是否为'0',是则不输入`,
        check: () => amountRef.value === '0' && inputText === '0',
        action: () => {inputText = ''},
      },
      {
        ruleHint: `输入 '1' ~ ' 9',判断当前金额是否为'0',是则替换为 '1' ~ ' 9'`,
        check: () => (/[1-9]/g).test(inputText) && amountRef.value === '0',
        action: () => {
          amountRef.value = inputText
          inputText = ''
        },
      },
      {
        ruleHint: `位数超过10位数字,则不能再输入,并提示`,
        check: () => (amountRef.value).replace('.', '').length > 10,
        action: () => {
          inputText = ''
          showNotify({ type: 'warning', position: 'bottom', message: '输入的位数不支持超过10位', })
        },
      },
    ]
    conditions
      ?.forEach(condition => {
        if(condition.check()) {condition.action()}
      })
    amountRef.value += inputText
  }

  const clearText = () => { amountRef.value = '0.00' }

  const backspaceText = () => {
    amountRef.value = amountRef.value.slice(0, -1)
    // 删空则补零
    if(amountRef.value === '') { amountRef.value = '0'}
  }

  return {
    amountRef,
    appendText,
    clearText,
    backspaceText,
  }
})

使用 useEventBus 解耦提示逻辑 ⇧

@/shared/events/useGlobalHintsBus.ts 全局提示事件总线

1
2
3
4
5
6
7
8
import { useEventBus } from '@vueuse/core'
import type { NotifyOptions } from 'vant'

export type GlobalHintPayload = string | NotifyOptions

export const useGlobalHintsBus = () => {
  return useEventBus<GlobalHintPayload>('global-hints')
}

@/modules/items/itemEvents.ts 记账相关事件中写数字长度限制提示事件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { type GlobalHintPayload, } from '@/shared/events/useGlobalHintsBus.ts'
import { showNotify } from 'vant'

export const numberLimitListener = (hint?: GlobalHintPayload) => {
  if (typeof hint === 'string') {
    showNotify({ type: 'warning', position: 'bottom', message: hint })
  } else if (hint && typeof hint === 'object') {
    showNotify(hint)
  } else {
    showNotify({ type: 'warning', position: 'bottom', message: '输入的数字长度不支持超过10位' })
  }
}

@/stores/useNumpadAmountStore.ts 中发布事件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useGlobalHintsBus } from '@/shared/events/useGlobalHintsBus.ts'

export const useNumpadAmountStore = defineStore('numpadAmount', () => {
  const amountRef = ref('0.00')
  const { emit } = useGlobalHintsBus()

  const appendText = (inputText: string) => {
    const conditions = [
      {
        ruleHint: `输入时,如果当前金额为'0.00',则清空金额`,
        // ...
      },
      {
        ruleHint: `小数点后已经有两位数字,则不能再输入`,
        // ...
      },
      {
        ruleHint: `已经有'.',则不能再输入'.'`,
        // ...
      },
      {
        ruleHint: `输入'.',判断当前金额是否为空,是则首位补零`,
        // ...
      },
      {
        ruleHint: `输入 '0',判断金额是否为'0',是则不输入`,
        // ...
      },
      {
        ruleHint: `输入 '1' ~ ' 9',判断当前金额是否为'0',是则替换为 '1' ~ ' 9'`,
        // ...
      },
      {
        ruleHint: `位数超过10位数字,则不能再输入,并提示`,
        check: () => amountRef.value.replace('.', '').length >= 10,
        action: () => {
          inputText = ''
          emit({ type: 'warning', position: 'bottom', message: '输入的数字长度不支持超过10位' })
        },
      },
    ]
    conditions?.forEach((condition) => {
      if (condition.check()) {
        condition.action()
      }
    })
    amountRef.value += inputText
  }

  const clearText = () => {
    amountRef.value = '0.00'
  }

  const backspaceText = () => {
    amountRef.value = amountRef.value.slice(0, -1)
    // 删空则补零
    if (amountRef.value === '') {
      amountRef.value = '0'
    }
  }

  return {
    amountRef,
    appendText,
    clearText,
    backspaceText,
  }
})

@/modules/items/Numpad.tsx 注册事件监听

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import { defineComponent, onBeforeUnmount } from 'vue'
import s from '@/modules/items/Numpad.module.scss'
import { cn } from 'cn'
import { SvgIcon } from '@/components/icons/SvgIcon.tsx'
import { useGlobalHintsBus, } from '@/shared/events/useGlobalHintsBus.ts'
import { numberLimitListener } from '@/modules/items/itemEvents.ts'
import { useNumpadButtons } from '@/modules/items/useNumpadButtons.ts'

export const Numpad = defineComponent({
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Numpad',
  setup(/* _props, _ctx */) {
    const {on, off,} = useGlobalHintsBus()
    const unsubscribe = on(numberLimitListener)
    onBeforeUnmount(() => { off(numberLimitListener);unsubscribe() })
    const numberSizeClass = (text: string) =>
      (/[0-9|dot]/g.test(text) ? cn('text-18px') : '')
    const {numpadButtons}  = useNumpadButtons()
    return () => (
      <div
        class={cn(
          'grid grid-cols-[repeat(4,1fr)] grid-rows-[repeat(4,56px)]',
          'bg-[var(--pad-border-color)] gap-1px p-t-1px',
          s['button-wrapper'],
        )}
        style={{
          'grid-template-areas': `
          'btn_1 btn_2 btn_3 btn_clear'
          'btn_4 btn_5 btn_6 btn_backspace'
          'btn_7 btn_8 btn_9 btn_submit'
          'btn_0 btn_0 btn_dot btn_submit'
          `,
        }}>
        {numpadButtons.map((buttonItem) => (
          <button
            type="button"
            key={buttonItem.text}
            data-btn-text={`btn_${buttonItem.id}`}
            onClick={buttonItem.onClick}
            style={{
              'grid-area': `btn_${buttonItem.id}`,
            }}
            class={cn(
              'flex justify-center items-center font-bold',
              'bg-[var(--pad-button-bg-color)] b-unset',
              buttonItem?.extraClass,
              numberSizeClass(buttonItem.text),
              s['button-item'],
            )}>
            {buttonItem.hasIcon ? <SvgIcon name={buttonItem.iconName} /> : buttonItem.text}
          </button>
        ))}
      </div>
    )
  },
})

单独拆分数字按键列表列表 @/modules/items/useNumpadButtons.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
import type { SvgIconName } from '@svgoStore'
import { cn } from 'cn'
import { useNumpadAmountStore } from '@/stores/useNumpadAmountStore.ts'

type ButtonItem<T extends boolean = boolean> = {
  id: string
  text: string
  onClick: () => void
  extraClass?: string
} & (T extends true
  ? {
      hasIcon: T
      iconName: SvgIconName
    }
  : {
      hasIcon?: false
      iconName?: never
    })

export const useNumpadButtons = () => {
  const { appendText, clearText, backspaceText } = useNumpadAmountStore()
  const numpadButtons: ButtonItem[] = [
    { id: '1', text: '1', onClick: () => appendText('1') },
    { id: '2', text: '2', onClick: () => appendText('2') },
    { id: '3', text: '3', onClick: () => appendText('3') },
    { id: 'clear', text: Math.random() > 0.5 ? '归零' : '清空', onClick: () => clearText() },
    { id: '4', text: '4', onClick: () => appendText('4') },
    { id: '5', text: '5', onClick: () => appendText('5') },
    { id: '6', text: '6', onClick: () => appendText('6') },
    {
      id: 'backspace',
      text: '退格',
      onClick: () => backspaceText(),
      hasIcon: true,
      iconName: 'backspace',
      extraClass: cn('children:(size-1.5em)'),
    },
    { id: '7', text: '7', onClick: () => appendText('7') },
    { id: '8', text: '8', onClick: () => appendText('8') },
    { id: '9', text: '9', onClick: () => appendText('9') },
    {
      id: 'submit',
      text: '提交',
      onClick: () => {
        clearText()
      },
      extraClass: cn('bg-[var(--pad-submit-button-bg-color)] text-[var(--button-text-color)]'),
    },
    { id: '0', text: '0', onClick: () => appendText('0') },
    {
      id: 'dot',
      text: 'dot',
      onClick: () => appendText('.'),
      hasIcon: true,
      iconName: 'decimal_point',
      extraClass: cn('children:(size-2em translate-y-[-9px] font-extrabold)'),
    },
  ]

  return { numpadButtons }
}

·未完待续·

参考文章

相关文章


  • 作者: Joel
  • 文章链接:
  • 版权声明
  • 非自由转载-非商用-非衍生-保持署名