Seeking assistance from anyone who can help me out. I have a popup and a button, and when I click the button, the popup window should open. Additionally, when I click outside the popup or on the button, the popup should hide.
https://i.sstatic.net/vDZ7L.png
I've implemented an example in a sandbox (unfortunately, it works locally but not in the sandbox environment. The code base is the same, and I'm puzzled by the reason for the issue in the sandbox. Hopefully, the example will be helpful)
Here's the directive I've implemented:
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 markup example:
<template>
<div class="component">
<button ref="button" @click="isDisplay = true">Create</button>
<div v-if="isDisplay" class="popup-box" 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>
Global 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');
It works successfully... When I click the create button, 'isDisplay' is set to true (click event) and then false (directive), which is a problem I'm struggling to fix. I've tried using a ref for the button, but I'm not clear on how to handle the ref attribute in the directive (I couldn't find a way to check the ref and current click event to understand where the click event is triggered).