I need to test (not trigger) if a click is done inside or outside a child component, including the DOM elements from this child and the sub-children.
I was using this code inside the child component with a ref on the main <div>
, it works well, but I need the test to be executed from the parent element and it doesn't work this way :
mounted() {
window.addEventListener('click', this.handleClickOutside);
}
methods: {
handleClickOutside(event) {
let targetElement = this.$refs.element;
if (!targetElement.contains(event.target)) {
console.log("click")
}
},
}
When trying to add the same code in the parent with a ref on the component, I get the error : targetElement.contains is not a function
.
I guess this is because the Vue component doesn't implement the contains method, so is there a way to achieve the same test from the parent side ?
Just use an event handler in the template on the parent element <div @click="handleClickOutside">...</div>
. Since the click event is bubbling you will get clicks from the div's children elements.