I am searching for a solution to automatically close a component when there is a click outside of the element.
I attempted to use an addEventListener
for this purpose.
Although it successfully closes the component, it encounters an issue where it fails to reopen once closed.
window.addEventListener('click', function(e){
if (document.getElementById('shopcartpreview').contains(e.target)){
console.log("Clicked in Box");
} else{
console.log("Clicked outside Box");
$('#shopcartpreview').hide();
}
})
Is there a better approach to handle this scenario?
<template>
<div id="shopcartpreview" v-if="carthover">
<div class="cartitem" v-for="item in cartitems">
<div class="cartitempic"><img class="productImg" width="80px" height="80px" v-bind:src="'assets/products/' + item.image"></div>
<div class="cartitemdetails">
<div class="cartitemname">{{item.name}}</div>
<div class="cartitemqty">1 X </div>
<div class="cartitemprice">€{{item.unit_price}}</div>
</div>
<div class="cartitemdelete">
<img src="assets/images/icon-bin.png" width="15px" height="15px">
</div>
</div>
<div class="carttotal">
<div class="carttotaltext">TOTAL:</div>
<div class="carttotalprice">€2,860.00</div>
</div>
<div class="cartcheckouttbn">PROCEED TO CHECKOUT</div>
<div class="viewcart">VIEW CART</div>
</div>
</template>
<script>
module.exports = {
data: function () {
return{
cartitems: 0,
carthover: false,
}
},
created(){
EventBus.$on('addToCart', (payload) =>{
this.cartitems = payload
}),
EventBus.$on('mouseover', (carthover) =>{
this.carthover = carthover
})
}
}
</script>