一、问题描述

在使用elementUI 的时候,有个组件是Dropdown 下拉菜单, 鼠标点击或者悬浮的时候,菜单出现,但是,当点击其他地方的时候,菜单消失,想搞明白是如何实现的,最终发现是使用“事件委托”

二、例子

2.1 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) {
    // 阻止事件冒泡,则不会触发window的clcik事件
    eventObj.stopPropagation();
}
</script>
</html>

2.2 Vue组件实现事件委托

  1. 组件加载,给window添加事件
  2. 组件销毁,给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.$emit("hide");
        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>
Logo

前往低代码交流专区

更多推荐