本文主要是介绍vue实现esc关闭div弹窗的自定义指令,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
弹窗是 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
<divv-div-esc-close="hideDialog"class="dialogBox">
</div>
<script>hideDialog() {// doSomething...}
</script>
这篇关于vue实现esc关闭div弹窗的自定义指令的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!