From a4a2a3cb0f33cb31c981a4a4146150bb3e4a3b5d Mon Sep 17 00:00:00 2001 From: neverland Date: Sat, 7 Aug 2021 16:01:11 +0800 Subject: [PATCH] feat(@vant/use): add useCustomFieldValue (#9200) * feat(@vant/use): add useCustomFieldValue * chore: upd --- packages/vant-use/src/index.ts | 1 + .../vant-use/src/useCustomFieldValue/index.ts | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 packages/vant-use/src/useCustomFieldValue/index.ts diff --git a/packages/vant-use/src/index.ts b/packages/vant-use/src/index.ts index d1f1ee007..d5e5ea087 100644 --- a/packages/vant-use/src/index.ts +++ b/packages/vant-use/src/index.ts @@ -8,4 +8,5 @@ export * from './useWindowSize'; export * from './useScrollParent'; export * from './useEventListener'; export * from './usePageVisibility'; +export * from './useCustomFieldValue'; export * from './onMountedOrActivated'; diff --git a/packages/vant-use/src/useCustomFieldValue/index.ts b/packages/vant-use/src/useCustomFieldValue/index.ts new file mode 100644 index 000000000..f94066539 --- /dev/null +++ b/packages/vant-use/src/useCustomFieldValue/index.ts @@ -0,0 +1,24 @@ +import { watch, inject, InjectionKey, Ref } from 'vue'; + +export type CustomFieldInjectionValue = { + customValue: Ref<(() => unknown) | undefined>; + resetValidation: () => void; + validateWithTrigger: (trigger: 'onBlur' | 'onChange' | 'onSubmit') => void; +}; + +export const CUSTOM_FIELD_INJECTION_KEY: InjectionKey = Symbol( + 'van-field' +); + +export function useCustomFieldValue(customValue: () => unknown) { + const field = inject(CUSTOM_FIELD_INJECTION_KEY, null); + + if (field && !field.customValue.value) { + field.customValue.value = customValue; + + watch(customValue, () => { + field.resetValidation(); + field.validateWithTrigger('onChange'); + }); + } +}