javascript - Vue 使用同一指令两次

标签 javascript vue.js directive

我有全局指令来在用户单击时隐藏模式:

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/

相关文章:

javascript - 从现有 JSON 对象构建新 JS 对象的最佳方法是什么?

vue.js - vuejs 将数据传递给模板 html 属性

javascript - 变量被分配了一个值,但在 Vue 数据对象中声明它并在方法中使用它时从未使用过

angularjs - 如何在AngularJs中实际使用ng-Cloak指令?

javascript - 将 Service 注入(inject) Directive AngularJS 和数据绑定(bind)中。

javascript - 从 JavaScript 中的动态数据集动态创建条件

javascript - 如何从三个函数向外部获取值并实时更新?

javascript - Angular 不渲染模板主要和常见的是什么

vue.js - Vue 3 - 使特定的类属性具有反应性

java - Freemarker 中的嵌套指令参数