I am using a custom click-outside
directive from this post:
This is my element:
<div class="datepicker panel panel-default" v-click-outside="close">
The custom directive:
module.exports = {
bind(el, binding, vnode) {
el.event = (event) => {
// Check that click was outside the el and his children.
if (!(el === event.target || el.contains(event.target))) {
console.log('Clicked outside');
// Call the method provided as the attribute value.
vnode.context[binding.expression](event);
}
};
document.body.addEventListener('click', el.event);
},
unbind(el) {
document.body.removeEventListener('click', el.event);
}
};
It works and to my knowledge the bind takes place on render of the element. Because I only want the click event to be registered when my datepicker is in view I wrapped it with a v-if
.
The problem is that when I use a button to toggle the display of the v-if
on the datepicker, the close
method from the directive immediately fires.
It seems that the event within bind
takes places before the element is even shown, therefore it closes immediately and nothing is shown at all.
This looks like pretty strange behavior singe the button is responsible for showing the datepicker and I would expect the bind to take place when the datepicker has rendered. Not at the same time or before.
Now it seems to take place even before the element has fully rendered. This causes my display button to cause a v-click-outside event.
What is causing this?
Edit:
Made a Jsfiddle to demonstrate this problem(open console):