检测nuxt中元素外部的点击 [英] Detect click outside element in nuxt
本文介绍了检测nuxt中元素外部的点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 nuxt 项目.我需要编写一个 click-outside 指令,通过它我可以检测元素的外部点击以关闭它们.我该如何实施?
解决方案
答案是在你的插件中创建一个 directives.js 文件并在 config.nuxt.js 文件中注册它.directives.js 文件的内容如下:
从'vue'导入Vue;Vue.directive('click-outside', {绑定:函数(el,绑定,vnode){el.clickOutsideEvent = 函数(事件){//在这里我检查点击是否在 el 和他的孩子之外if (!(el == event.target || el.contains(event.target))) {//如果是,则调用属性值中提供的方法vnode.context[binding.expression](event);}};document.body.addEventListener('click', el.clickOutsideEvent)},解除绑定:函数(el){document.body.removeEventListener('click', el.clickOutsideEvent)},});
然后您可以在您想要的任何元素上使用它并执行您的功能.示例:
I have a nuxt project. I need to write a click-outside directive by which I can detect outside clicks of elements to close them. How can I implement it?
解决方案
The answer is to create a directives.js file in your pulgins and register it in config.nuxt.js file. The content of the directives.js file is as follows:
import Vue from 'vue';
Vue.directive('click-outside', {
bind: function (el, binding, vnode) {
el.clickOutsideEvent = function (event) {
// here I check that click was outside the el and his childrens
if (!(el == event.target || el.contains(event.target))) {
// and if it did, call method provided in attribute value
vnode.context[binding.expression](event);
}
};
document.body.addEventListener('click', el.clickOutsideEvent)
},
unbind: function (el) {
document.body.removeEventListener('click', el.clickOutsideEvent)
},
});
Then you can use it on any element that you want and execute your function. Example:
<div v-click-outside="closeDropdown"></div>
这篇关于检测nuxt中元素外部的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文