typescript

import type { DirectiveBinding } from "vue";

export default {
  bind(el: HTMLElement, binding: DirectiveBinding<Function>) {
    //声明一个给document绑定的事件
    function documentClick(event: Event) {
      const target = event.target as unknown as Node;
      if (el.contains(target)) {
        return false;
      }
      //如果绑定了关闭函数就触发
      if (binding.expression) {
        binding.value(event);
      }
    }
    // 给当前元素绑定个私有变量,方便在unbind中可以解除事件监听
    el["__clickBlankSpaceClose__"] = documentClick;
    document.addEventListener("click", documentClick);
  },
  unbind(el: HTMLElement) {
    // 解除事件监听
    document.removeEventListener("click", el["__clickBlankSpaceClose__"]);
    Reflect.deleteProperty(el, "__clickBlankSpaceClose__");
  },
};

使用

import Vue from "vue";

import clickBlankSpaceClose from "./components/clickBlankSpaceClose";
Vue.directive("clickBlankSpaceClose", clickBlankSpaceClose);
<template>
 <div class="menu-wrap" v-clickBlankSpaceClose="onCloseList">
   ...
 </div>
</template>

onCloseList为具体的关闭的方法,比如控制一个变量的true和false

分类: vue 项目实战 标签: vue自定义指令空白区域关闭

评论

暂无评论数据

暂无评论数据

目录