首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检测对子程序vue/nux自定义指令的单击

如何检测对子程序vue/nux自定义指令的单击
EN

Stack Overflow用户
提问于 2020-05-06 15:47:07
回答 1查看 163关注 0票数 0

当我尝试使用Vue.js自定义指令时,我很挣扎,我试图创建带有内部搜索的下拉列表。我不知道孩子们什么时候点击

代码语言:javascript
复制
<div v-dropdown-directive class="dropdown">
  <div class="title">This is dropdown title</div>
  <div class="close">Close dropdown</div>
</div>

指令

代码语言:javascript
复制
import Vue from 'vue'
Vue.directive('dropdown-directive', {
  bind (el) {
    el.event = (e) => {
      if (el === e.target) {
        console.log('parent clicked')
        el.classList.add('open') // this will add class open to parent, so dropdown will open
      } else if (el.contains(e.target)) {
        console.log('children clicked')
        // this is working, but when I click on children has class "title" i'ts also working,
        // I want only work when I click on children contain class "close"
      } else if (!el.contains(e.target)) {
        console.log('detect click outside')
        el.classList.remove('open')
      }
    }
  }
})
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-06 20:03:08

在下面的片段中:

  • 如果单击红色,它就是父元素
  • ,如果单击蓝色标题,则是标题元素
  • ,如果单击蓝色关闭,则是关闭元素
  • ,如果单击父元素,则显示在

之外。

代码语言:javascript
复制
Vue.directive('DropdownDirective', {
  bind(el, binding) {
    let type = binding.arg;
    const clickFunction = (e) => {
      if (e.target.classList.contains('close')) {
        console.log('close')
      } else if (e.target.classList.contains('title')) {
        console.log('title:', e.target.textContent)
      } else if (e.target === el) {
        console.log('parent')
      } else {
        console.log('outside')
      }
    }
    // adding a general eventListener, so you can check for clicks outside
    window.addEventListener(type, clickFunction);
  }
})

new Vue({
  el: "#app"
})
代码语言:javascript
复制
.dd-item {
  width: 50%;
  background: blue;
}
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-dropdown-directive:click class="dropdown" style="background-color:red;">
    <div class="title dd-item">This is dropdown title</div>
    <div class="close dd-item">Close dropdown</div>
  </div>
</div>

重点是:

  • 您必须定义要侦听的事件。在片段中,我将它定义为指令(:click)的一个参数,并在绑定指令
  • 中使用该参数,您必须将侦听器添加到该事件(与任何应该侦听事件的JS代码一样)
  • ,您必须定义该事件的回调函数。

关于Vue指令的更多信息:https://v2.vuejs.org/v2/guide/custom-directive.html

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61639428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档