How to detect click outside in Nuxt

Nuxt guide logo

Detect click in Nuxt 2

This tutorial is using Nuxt's Composition API.

In Nuxt 2, use @focusout directive.

Inside the template tag:

html
<template>
  <button @focusout="triggerClickOutside()">
  </button>
</template>

If the HTML element is not focus–able like a div or a span, we need to set tabindex on this element.

Here, we set the HTML element to have tabindex:

html
<template>
  <div @focusout="triggerClickOutside()" tabindex="0">
  </div>
</template>

Inside the script tag:

typescript
<script>
  import { defineComponent } from '@nuxtjs/composition-api';
  
  export default defineComponent({
    setup() {
      const triggerClickOutside = () => {
        // Do something here
      }
    }

    return {
      triggerClickOutside
    }
  })
</script>
Previous post How to get current route name in Nuxt
Next post How to use Sass in Nuxt 3