Vue 3 指令处理程序不作为基本指令工作

Vue 3 directive handler not working as basic directives

我已经创建了一个指令,但我无法让它与“已执行”处理程序一起工作: 以下是指令的创建方式:

vueApp.directive('click-outside', {
            beforeMount(el, binding, vnode) {
                el.clickOutsideEvent = (evt) => {
                    evt.stopPropagation();
                    if (!(el === evt.target || el.contains(evt.target))) {
                        binding.value(evt, el);
                    }
                }
                // Wait 1 frame otherwise a potential click that mounted the element will immediately trigger a click-outside event:
                window.requestAnimationFrame(() => { document.addEventListener('click', el.clickOutsideEvent) });
            },
            unmounted(el) {
                document.removeEventListener('click', el.clickOutsideEvent);
            },
        });

如果我添加一个处理程序,例如 close 将起作用(将调用关闭函数):

<div v-if="opened" v-click-outside="close">
    Some content
</div>

但是如果我使用一些脚本就会失败:

<div v-if="opened" v-click-outside="opend = false">
    Some content
</div>

<div v-if="opened" v-click-outside="close()">
    Some content
</div>

这些给我一个错误:Uncaught TypeError: binding.value is not a function

此行为适用于例如@click 指令 @click="opened = !opened"@click="open()" 所以问题是我是否以及如何更改指令以使其在所有情况下都有效。

v-bind 不同,您的指令的绑定值会在呈现模板时立即计算。 @vue/compiler-sfcv-bind 值中的表达式转换为函数,但您必须为自定义指令手动执行此操作:

<div v-if="opened" v-click-outside="() => opened = false">
    Some content                    
</div>
<div v-if="opened" v-click-outside="() => close()">
    Some content                    
</div>

demo