vue实现esc关闭div弹窗的自定义指令
vue中实现可拖拽的div能esc关闭的指令(类似el-dialog的esc关闭弹窗效果)
·
弹窗是 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>
更多推荐
已为社区贡献2条内容
所有评论(0)