Skip to content

useClickAway

Intro

Triggers a callback when user clicks outside of the target element.

Usage

Basic Usage

html
<div ref="root" />
js
import { ref } from 'vue';
import { useClickAway } from '@vant/use';

export default {
  setup() {
    const root = ref();
    useClickAway(root, () => {
      console.log('click outside!');
    });

    return { root };
  },
};

Custom Event

html
<div ref="root" />
js
import { ref } from 'vue';
import { useClickAway } from '@vant/use';

export default {
  setup() {
    const root = ref();
    useClickAway(
      root,
      () => {
        console.log('touch outside!');
      },
      { eventName: 'touchstart' },
    );

    return { root };
  },
};

API

Type Declarations

ts
type Options = {
  eventName?: string;
};

function useClickAway(
  target:
    | Element
    | Ref<Element | undefined>
    | Array<Element | Ref<Element | undefined>>,
  listener: EventListener,
  options?: Options,
): void;

Params

NameDescriptionTypeDefault Value
targetTarget element, support multiple elementsElement | Ref<Element> | Array<Element | Ref<Element>>-
listenerCallback function when the outside is clickedEventListener-
optionsOptionsOptions{ eventName: 'click' }

Options

NameDescriptionTypeDefault Value
eventNameEvent namestringclick

Enterprise-level mobile solution based on Vant