文章目录
问题描述例子html事件委托简单案例Vue组件实现事件委托
问题描述
在使用elementUI 的时候,有个组件是Dropdown 下拉菜单, 鼠标点击或者悬浮的时候,菜单出现,但是,当点击其他地方的时候,菜单消失,想搞明白是如何实现的,最终发现是使用“事件委托”
例子
html事件委托简单案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document
</title>
</head>
<style>
.box{
height: 100px;
width: 100px;
display: inline-block;
border: 1px solid red;
}
.little{
height: 50px;
width: 50px;
display: inline-block;
border: 1px solid blue;
}
</style>
<body>
<div class="box" onclick="isHide(event)" id="mymodal">
<div class="little">
实现事件委托功能
</div>
</div>
</body>
<script>
window.onclick = function (eventObj) {
console.log(eventObj);
debugger
document.getElementById("mymodal").style.display = "none";
}
function isHide (eventObj) {
eventObj.stopPropagation();
}
</script>
</html>
Vue组件实现事件委托
组件加载,给window添加事件组件销毁,给window添加的事件要删除
<template>
<div class="my-tips" @click="isHideAction" id="myTipsComp">
点击我就不会消失,否则就会消失
<div class="little">我是子组件
</div>
</div>
</template>
<script>
export default {
mounted: function() {
var that = this;
setTimeout(function () {
that.eventLive();
}, 50)
},
beforeDestroy: function () {
window.removeEventListener("click", this.liveAction, false)
},
methods: {
eventLive: function() {
this.addEvent(window, "click", this.liveAction);
},
liveAction: function (eventObj) {
console.log(eventObj);
console.log(this);
this.$destroy();
document.getElementById("myTipsComp").remove();
},
isHideAction: function (eventObj) {
eventObj.stopPropagation();
},
addEvent: function(el, type, fun) {
if (el.addEventListener) {
el.addEventListener(type, fun, false);
} else if (el.attachEvent()) {
el.attachEvent("on" + type, fun, false);
} else {
return false;
}
}
}
};
</script>
<style scoped lang='scss'>
.my-tips {
height: 100px;
width: 100px;
display: inline-block;
border: 1px solid red;
.little {
height: 50px;
width: 50px;
display: inline-block;
border: 1px solid blud;
}
}
</style>