首页 > 解决方案 > Is there a way to close a vue component by clicking outside of it?

问题描述

I am looking for a way to close a component when there it a click outisde of the element.

I tried an addEventListener. This closes the component but after being closed it will not open again.

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 way to accomplish this?

<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>

标签: javascriptvue.js

解决方案


我在div组件的末尾创建了一个元素,如下所示:

<div v-if="isPopup" class="outside" v-on:click="away()"></div>

其中.outsideclass 在 CSS 中指定如下:

.outside {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0px;
  left: 0px;
}

并且away()是 Vue 实例中的一个方法:

away() {
 this.isPopup = false;
}

很简单,效果很好。


推荐阅读