Home > front end >  How ignore directive event if out side click is in the button? ( Vue 3)
How ignore directive event if out side click is in the button? ( Vue 3)

Time:10-03

May be somebody can help me. I have the popup and button, when I click to create button the popup window has to open and when I click outside or on button the popup has to hide

enter image description here

I implement the example in sandbox (unfortunately it works locally but doesn't work in sandbox, I can't understand the reason of problem in sandbox, code base the same, I hope the example will be useful)

I implement directive:

export default {
    name: 'click-outside',

    mounted: function (el, binding, vnode) {
      el.clickOutsideEvent = function (event) {
        event.stopPropagation();
        if (!(el === event.target || el.contains(event.target))) {
          binding.value;
      }
    };
    document.addEventListener('click', el.clickOutsideEvent);
  },
  unmounted: function (el) {
    document.removeEventListener('click', el.clickOutsideEvent);
  },
};

simple make up:

<template>
  <div >
    <button ref="button" @click="isDisplay = true">Create</button>
    <div v-if="isDisplay"  v-click-outside="onClose">
      Test Popup Box
    </div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      isDisplay: true,
    };
  },

  method: {
    onClose() {
      this.isDisplay = false;
    },
  },
};
</script>

<style scoped>
.component {
  display: flex;
  justify-content: column;
}
.popup-box {
  position: absolute;
  left: 50%;
  top: 50px;
  transform: translateX(-50%);
  background: #f0f8ff;
  border-radius: 1px;
  box-shadow: 1px 1px 15px 0 rgba(0, 0, 0, 0.2);
  padding: 40px;
  color: #555585;
}
</style>

and make global the connection for directive:

import { createApp } from 'vue';
import App from './App.vue';
import ClickOutside from './directives/clickOutside.js';

const app = createApp(App);

app.directive('click-outside', ClickOutside);

app.mount('#app');

in the result Yes it works....

when I am clicking the create button 'isDisplay' set firstly as true (click event) then false (directive) and it is problem which I don't know how to fix, I tried to use ref for button but I don't clearly understand how to ingore the ref attribute in directive ( I didn't find any place where I can check ref and current click with, to understand in which place click event is triggered)

CodePudding user response:

With your code base you need to assign v-click-outside on your component, or on the inner wrapper

<template>
    <div  v-click-outside="onClose">
        <button ref="button" @click="isDisplay = true">Create</button>
        <div v-if="isDisplay" >
            Test Popup Box
        </div>
    </div>
</template>

And in your code you have a misspell in method field. You need to methods instead

  • Related