我有一个 nuxt 项目。我需要编写一个 click-outside 指令,通过它我可以检测元素的外部点击以关闭它们。我该如何实施?
Sha*_*kia 12
答案是在插件中创建一个directives.js 文件并将其注册到config.nuxt.js 文件中。directives.js 文件内容如下:
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)
},
});
Run Code Online (Sandbox Code Playgroud)
然后您可以在任何您想要的元素上使用它并执行您的函数。
例如:
<div v-click-outside="closeDropdown"></div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9645 次 |
| 最近记录: |