javascript - 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>
解决方案
我在div
组件的末尾创建了一个元素,如下所示:
<div v-if="isPopup" class="outside" v-on:click="away()"></div>
其中.outside
class 在 CSS 中指定如下:
.outside {
width: 100vw;
height: 100vh;
position: fixed;
top: 0px;
left: 0px;
}
并且away()
是 Vue 实例中的一个方法:
away() {
this.isPopup = false;
}
很简单,效果很好。
推荐阅读
- android - 错误:没有方法签名:com.crashlytics.tools.gradle.CrashlyticsPlugin.findObfuscationTransformTask()
- javascript - 使用 JavaScript 更改 HTML 选择元素中的选项
- node.js - Node JS 邮件调度器
- python - 如何使用 ipv6 https 代理连接到网站
- css - 找不到或无法读取要导入的文件:bootstrap-sass
- android - 使用 ProGuard 后 Volley 总是抛出错误
- sql - “可重复读取”和“快照隔离”有什么区别
- c# - Unity如何比较两个数组的内容而不考虑顺序?
- magento2 - Magento 2 基础设施
- javascript - Cypress - addContext() 保留以前的失败计数并将其添加到 mochawesome 报告中的每个“it”场景中