useClickAway

介绍

监听点击元素外部的事件。

代码演示

基本用法

  1. <div ref="root" />
  1. import { ref } from 'vue';
  2. import { useClickAway } from '@vant/use';
  3. export default {
  4. setup() {
  5. const root = ref();
  6. useClickAway(root, () => {
  7. console.log('click outside!');
  8. });
  9. return { root };
  10. },
  11. };

自定义事件

通过 eventName 选项可以自定义需要监听的事件类型。

  1. <div ref="root" />
  1. import { ref } from 'vue';
  2. import { useClickAway } from '@vant/use';
  3. export default {
  4. setup() {
  5. const root = ref();
  6. useClickAway(
  7. root,
  8. () => {
  9. console.log('touch outside!');
  10. },
  11. { eventName: 'touchstart' }
  12. );
  13. return { root };
  14. },
  15. };

API

类型定义

  1. type Options = {
  2. eventName?: string;
  3. };
  4. function useClickAway(
  5. target: Element | Ref<Element | undefined>,
  6. listener: EventListener,
  7. options?: Options
  8. ): void;

参数

参数说明类型默认值
target绑定事件的元素Element | Ref<Element>-
listener点击外部时触发的回调函数EventListener-
options可选的配置项Options见下表

Options

参数说明类型默认值
eventName监听的事件类型stringclick

useClickAway - 图1