0

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).

2
  • This might be helpful stackoverflow.com/a/63910611/197546 Commented Apr 28, 2022 at 21:15
  • Thanks!! My problem was with the CSS and HTML my <body> Element was not all over the page. Commented May 1, 2022 at 10:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.