From 31ac5faa3a74348b6978083e207abc1fe56d7991 Mon Sep 17 00:00:00 2001 From: neverland Date: Sun, 21 Aug 2022 10:55:18 +0800 Subject: [PATCH] feat(@vant/use): useClickAway support multiple targets (#10948) --- packages/vant-use/src/useClickAway/index.ts | 14 +++++++++++--- .../vant/docs/markdown/use-click-away.en-US.md | 2 +- .../vant/docs/markdown/use-click-away.zh-CN.md | 10 +++++----- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/vant-use/src/useClickAway/index.ts b/packages/vant-use/src/useClickAway/index.ts index b36312dba..9099459dc 100644 --- a/packages/vant-use/src/useClickAway/index.ts +++ b/packages/vant-use/src/useClickAway/index.ts @@ -7,7 +7,10 @@ export type UseClickAwayOptions = { }; export function useClickAway( - target: Element | Ref, + target: + | Element + | Ref + | Array>, listener: EventListener, options: UseClickAwayOptions = {} ) { @@ -18,8 +21,13 @@ export function useClickAway( const { eventName = 'click' } = options; const onClick = (event: Event) => { - const element = unref(target); - if (element && !element.contains(event.target as Node)) { + const targets = Array.isArray(target) ? target : [target]; + const isClickAway = targets.every((item) => { + const element = unref(item); + return element && !element.contains(event.target as Node); + }); + + if (isClickAway) { listener(event); } }; diff --git a/packages/vant/docs/markdown/use-click-away.en-US.md b/packages/vant/docs/markdown/use-click-away.en-US.md index 32ec70cd8..7374ca484 100644 --- a/packages/vant/docs/markdown/use-click-away.en-US.md +++ b/packages/vant/docs/markdown/use-click-away.en-US.md @@ -74,7 +74,7 @@ function useClickAway( | Name | Description | Type | Default Value | | --- | --- | --- | --- | -| target | Target element | _Element \| Ref\_ | - | +| target | Target element, support multiple elements | _Element \| Ref\ \| Array\>_ | - | | listener | Callback function when the outside is clicked | _EventListener_ | - | | options | Options | _Options_ | `{ eventName: 'click' }` | diff --git a/packages/vant/docs/markdown/use-click-away.zh-CN.md b/packages/vant/docs/markdown/use-click-away.zh-CN.md index b13d76319..291314f94 100644 --- a/packages/vant/docs/markdown/use-click-away.zh-CN.md +++ b/packages/vant/docs/markdown/use-click-away.zh-CN.md @@ -74,11 +74,11 @@ function useClickAway( ### 参数 -| 参数 | 说明 | 类型 | 默认值 | -| -------- | ------------------------ | -------------------------- | ------ | -| target | 绑定事件的元素 | _Element \| Ref\_ | - | -| listener | 点击外部时触发的回调函数 | _EventListener_ | - | -| options | 可选的配置项 | _Options_ | 见下表 | +| 参数 | 说明 | 类型 | 默认值 | +| --- | --- | --- | --- | +| target | 绑定事件的元素,支持传入数组来绑定多个元素 | _Element \| Ref\ \| Array\>_ | - | +| listener | 点击外部时触发的回调函数 | _EventListener_ | - | +| options | 可选的配置项 | _Options_ | 见下表 | ### Options