我有全局指令来在用户单击时隐藏模式:
Vue.directive('click-outside', {
bind(el, binding, vNode) {
el.clickOutside = event => {
if (!(el == event.target || el.contains(event.target))) {
vNode.context[binding.expression](event);
event.stopPropagation();
}
}
document.body.addEventListener('click', el.clickOutside)
},
unbind(el) {
document.removeEventListener('click', el.clickOutside)
el.clickOutside = null
}
});
接下来我使用这个指令:
<img src="noti.png" id="1" v-click-outside="onClickOutside('notification')">
<img src="dots.png" id="2" v-click-outside="onClickOutside('profile')">
我遇到问题,因为我无法在一个组件上使用相同的指令。 Vue 返回错误:
vNode.context[binding.expression] is not a function
我找到了这个query ,但答案对我没有帮助。
例如,当将 console.log
添加到指令并单击第一个 img
指令时,将执行两次。
我如何检测(在指令中)点击了哪个 img
?
最佳答案
渲染模板时,将立即评估您传递给自定义指令的值。这与 v-on
不同,Vue 模板编译器具有特殊行为,它会自动将其包装在函数中。
我在 this answer 中更详细地解释了这一点.
我不知道这是否能完全解决你的问题,但至少你需要做这样的事情:
<img src="noti.png" id="1" v-click-outside="() => onClickOutside('notification')">
关于javascript - Vue 使用同一指令两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260978/