在vue中监听click,实现点击弹出框外部将弹出框关闭
一个比较老的项目,弹出框使用原生的 show hidden方式实现,为了兼容当前代码,在vue中使用dom对页面进行监听
html部分
<div class="item" @click="jumpModule('/homepage')"> ===》这个是包裹你需要控制显隐藏的外层div click写在这里
<!-- 下拉内容 -->
<div class="downContent" v-show="isopen"> ===》这个是下拉框 isopen在这里生效 内容和css自己定义
<div class="newspace"></div>
<div
class="downitem"
v-for="(item, index) in moduleList"
:key="item.id"
:class="[
index === moduleList.length - 1 ? 'goodList-final ' : '',
item.name === value ? 'wrodcolor ' : '',
item.id === preload ? 'preloadcss ' : '',
]"
@click="chooseModule(item.path, item.name)"
@mouseover="mouseOver(item.id)"
@mouseleave="mouseLeave"
>
<img
src="~@/assets/images/imgs/arrowIcon.png"
v-show="item.name === value"
alt=""
/>
{{ item.name }}
</div>
</div>
</div>
</div>
vue的data部分
isopen: false, //是否展开
vue的created部分
created() {
let _this = this
document.addEventListener('click',function(){ ---》监听页面中的click事件
if(_this.isopen == true){
//vue中用dom操作对象,可能有点说不过去,但是对这个老项目有效
document.getElementsByClassName("downContent")[0].style.display = "none"
_this.isopen = false
}
})
},
vue的methods事件
// 下拉点击事件
newselected() {
if (this.isopen) {
this.isopen = false;
} else {
this.isopen = true;
}
},
jumpModule0(e, num) {
this.num = num;
let path = e.target.getAttribute("data-path");
if (path) {
this.$router.push(path);
}
},