feat(@vant/use): useClickAway support multiple targets (#10948)

This commit is contained in:
neverland 2022-08-21 10:55:18 +08:00 committed by GitHub
parent 1e8187bc37
commit 31ac5faa3a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 9 deletions

View File

@ -7,7 +7,10 @@ export type UseClickAwayOptions = {
}; };
export function useClickAway( export function useClickAway(
target: Element | Ref<Element | undefined>, target:
| Element
| Ref<Element | undefined>
| Array<Element | Ref<Element | undefined>>,
listener: EventListener, listener: EventListener,
options: UseClickAwayOptions = {} options: UseClickAwayOptions = {}
) { ) {
@ -18,8 +21,13 @@ export function useClickAway(
const { eventName = 'click' } = options; const { eventName = 'click' } = options;
const onClick = (event: Event) => { const onClick = (event: Event) => {
const element = unref(target); const targets = Array.isArray(target) ? target : [target];
if (element && !element.contains(event.target as Node)) { const isClickAway = targets.every((item) => {
const element = unref(item);
return element && !element.contains(event.target as Node);
});
if (isClickAway) {
listener(event); listener(event);
} }
}; };

View File

@ -74,7 +74,7 @@ function useClickAway(
| Name | Description | Type | Default Value | | Name | Description | Type | Default Value |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| target | Target element | _Element \| Ref\<Element>_ | - | | target | Target element, support multiple elements | _Element \| Ref\<Element> \| Array\<Element \| Ref\<Element>>_ | - |
| listener | Callback function when the outside is clicked | _EventListener_ | - | | listener | Callback function when the outside is clicked | _EventListener_ | - |
| options | Options | _Options_ | `{ eventName: 'click' }` | | options | Options | _Options_ | `{ eventName: 'click' }` |

View File

@ -75,8 +75,8 @@ function useClickAway(
### 参数 ### 参数
| 参数 | 说明 | 类型 | 默认值 | | 参数 | 说明 | 类型 | 默认值 |
| -------- | ------------------------ | -------------------------- | ------ | | --- | --- | --- | --- |
| target | 绑定事件的元素 | _Element \| Ref\<Element>_ | - | | target | 绑定事件的元素,支持传入数组来绑定多个元素 | _Element \| Ref\<Element> \| Array\<Element \| Ref\<Element>>_ | - |
| listener | 点击外部时触发的回调函数 | _EventListener_ | - | | listener | 点击外部时触发的回调函数 | _EventListener_ | - |
| options | 可选的配置项 | _Options_ | 见下表 | | options | 可选的配置项 | _Options_ | 见下表 |