检测 nuxt 中元素外部的点击

Sha*_*kia 5 nuxt.js

我有一个 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)

  • 这给了我错误:``` v-click-outside.js?015b:9 Uncaught TypeError: vnode.context[binding.expression] is not a function at HTMLBodyElement.el.clickOutsideEvent ``` (2认同)