From 7e974b55d72b8ac0ab42ef722a2d1904c3e4e091 Mon Sep 17 00:00:00 2001 From: Vincent Ratier Date: Thu, 18 Jul 2024 12:51:01 +0100 Subject: [PATCH] feat(SelectMenu): handle function in `showCreateOptionWhen` prop (#1853) Co-authored-by: Benjamin Canac --- .../SelectMenuExampleCreatableFunction.vue | 60 +++++++++++++++++++ docs/content/2.components/select-menu.md | 12 ++++ src/runtime/components/forms/SelectMenu.vue | 8 ++- 3 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 docs/components/content/examples/SelectMenuExampleCreatableFunction.vue diff --git a/docs/components/content/examples/SelectMenuExampleCreatableFunction.vue b/docs/components/content/examples/SelectMenuExampleCreatableFunction.vue new file mode 100644 index 00000000..c766b58c --- /dev/null +++ b/docs/components/content/examples/SelectMenuExampleCreatableFunction.vue @@ -0,0 +1,60 @@ + + + diff --git a/docs/content/2.components/select-menu.md b/docs/content/2.components/select-menu.md index fad9c161..496de7a0 100644 --- a/docs/content/2.components/select-menu.md +++ b/docs/content/2.components/select-menu.md @@ -188,6 +188,18 @@ componentProps: --- :: +Pass a function to the `show-create-option-when` prop to control wether or not to show the create option. This function takes two arguments: the query (as the first argument) and an array of current results (as the second argument). It should return true to display the create option. + +The example below shows how to make the create option visible when the query is at least three characters long and does not exactly match any of the current results (case insensitive). + +::component-example +--- +component: 'select-menu-example-creatable-function' +componentProps: + class: 'w-full lg:w-48' +--- +:: + ## Popper Use the `popper` prop to customize the popper instance. diff --git a/src/runtime/components/forms/SelectMenu.vue b/src/runtime/components/forms/SelectMenu.vue index 843d202a..b151f9b3 100644 --- a/src/runtime/components/forms/SelectMenu.vue +++ b/src/runtime/components/forms/SelectMenu.vue @@ -265,7 +265,7 @@ export default defineComponent({ default: false }, showCreateOptionWhen: { - type: String as PropType<'always' | 'empty'>, + type: [String, Function] as PropType<'always' | 'empty' | ((query: string, results: any[]) => boolean)>, default: () => configMenu.default.showCreateOptionWhen }, placeholder: { @@ -494,7 +494,11 @@ export default defineComponent({ return null } } - + if (typeof props.showCreateOptionWhen === 'function') { + if (!props.showCreateOptionWhen(query.value, filteredOptions.value)) { + return null + } + } return ['string', 'number'].includes(typeof props.modelValue) ? query.value : { [props.optionAttribute]: query.value } })