Writing a custom directive on Vuejs 3, composition API in order to detect outside click

1.2k Views Asked by At

my first time trying directive with vue js3.

My goal: To detect a click outside the component with the directive and Vuejs 3, composition API.

My expected result: To change a Boolean value in each click outside the component 'CustomeMultiSelect.vue'.

My actual result: In any click, the Boolean value is changed.

Here is my 'App.vue'

<script lang="ts">
import CustomeMultiSelect from "./components/CustomeMultiSelect.vue";
import { ref } from "vue";
export default {
  components: {
    CustomeMultiSelect,
  },
  directives: {
    "click-outside": {
      mounted: function (el, binding) {
        console.log("in directive");
        const ourClickEventHandler = (event) => {
          if (!el.contains(event.target) && el !== event.target) {
            binding.value(event);
          }
        };
        el.__vueClickEventHandler__ = ourClickEventHandler;
        document.addEventListener("click", ourClickEventHandler);
      },
      unmounted: function (el) {
        document.removeEventListener("click", el.__vueClickEventHandler__);
      },
    },
  },
  setup() {
   let bool = ref(true);
   function test() {
    bool.value = !bool.value;
    console.log(bool.value);
   }
    return {
      test,
    };
  },
};
</script>

<template>
  <div v-click-outside="test">
    <CustomeMultiSelect/>
  </div>
</template>

I defined directive that on 'mounted' Hook will attached event 'click' to each element in the screen -> 'v-click-outside' on <'CustomeMultiSelect.vue'/>

Component 'CustomeMultiSelect.vue' is a child component of 'App.vue'. ('CustomeMultiSelect.vue' has 3 childs).

0

There are 0 best solutions below