弹窗是 div 实现的(非el-dialog),效果:按下esc,关闭弹窗

directive/divEscClose/divEscClose.js
export default {
  bind: function (el, binding, vnode) {
    let keydownHandler;
​
    const closeModal = () => {
      if (typeof binding.value === 'function') {
        binding.value();
      }
    };
​
    keydownHandler = e => {
      if (e.key === 'Escape') {
        closeModal();
      }
    };
​
    document.addEventListener('keydown', keydownHandler);
​
    vnode.context.$once('hook:beforeDestroy', () => {
      document.removeEventListener('keydown', keydownHandler);
    });
​
    // 将事件处理器存储在指令的私有变量中
    el._keydownHandler = keydownHandler;
  },
  unbind: function (el) {
    // 从元素中获取并移除事件监听器
    const keydownHandler = el._keydownHandler;
    if (keydownHandler) {
      document.removeEventListener('keydown', keydownHandler);
      delete el._keydownHandler; // 清理私有变量
    }
  },
}

directive/index.js
​​​​​​​import divEscClose from "@/directive/divEscClose/divEscClose";
​
const install = function (Vue) {
 Vue.directive("divEscClose", divEscClose);
};
​
export default install;
xxx.vue
<div
    v-div-esc-close="hideDialog"
    class="dialogBox">
</div>
​
<script>
    hideDialog() {
        // doSomething...
    }
</script>

Logo

前往低代码交流专区

更多推荐