检测点击外部元素


118

如何检测元素外部的点击?我正在使用Vue.js,因此它将不在模板元素内。我知道如何在Vanilla JS中执行此操作,但是我不确定在使用Vue.js时是否还有更合适的方法?

这是Vanilla JS的解决方案: div外部的Javascript Detect Click事件

我想我可以使用更好的方法来访问元素?


Vue组件是隔离的。因此检测外部变化毫无疑问,并且使用了反模式。
Raj Kamal

谢谢。我不确定如何在Vue组件中实现它。反模式仍然必须有一些最佳做法?

Vue.js组件是隔离的,这是对的,但是用于父子通信的方法不同。因此,应指定是否要检测组件内部,父组件,某些子组件或组件之间的任何关系,而不是检测某个元素外部的事件
Yerko Palma

感谢您的反馈。您有一些我可以跟进的例子或链接吗?

Answers:


95

只需设置一次自定义指令即可很好地解决:

Vue.directive('click-outside', {
  bind () {
      this.event = event => this.vm.$emit(this.expression, event)
      this.el.addEventListener('click', this.stopProp)
      document.body.addEventListener('click', this.event)
  },   
  unbind() {
    this.el.removeEventListener('click', this.stopProp)
    document.body.removeEventListener('click', this.event)
  },

  stopProp(event) { event.stopPropagation() }
})

用法:

<div v-click-outside="nameOfCustomEventToCall">
  Some content
</div>

在组件中:

events: {
  nameOfCustomEventToCall: function (event) {
    // do something - probably hide the dropdown menu / modal etc.
  }
}

在JSFiddle上的工作演示,有关警告的其他信息:

https://jsfiddle.net/Linusborg/yzm8t8jq/


3
我确实使用了vue clickaway,但我认为您的解决方案大致相同。谢谢。

56
这种方法在Vue.js 2中不再起作用。self.vm. $ emit调用给出错误消息。
Northernman

3
使用@blur也是一种选择,它可以更轻松地给出相同的结果:<input @ blur =“ hide”>其中hide:function(){this.isActive = false; }
爬行

1
答案应该被编辑到i'ts仅Vue.js 1状态
斯特凡格柏

167

有我使用的解决方案,该解决方案基于Linus Borg的答案,并且可以在vue.js 2.0中正常工作。

Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {
    el.clickOutsideEvent = function (event) {
      // here I check that click was outside the el and his children
      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)
  },
});

您使用v-click-outside以下方法绑定到它:

<div v-click-outside="doStuff">

这是一个小演示

您可以在https://vuejs.org/v2/guide/custom-directive.html#Directive-Hook-Arguments中找到有关自定义指令以及el,绑定,vnode含义的更多信息。


8
有效,但在Vue 2.0指令中不再有实例,因此未定义。vuejs.org/v2/guide/migration.html#Custom-Directives-simplified。我不知道为什么这种提琴奏效或何时进行了简化。(要解决,将“ this”替换为“ el”以将事件绑定到元素)
Busata

1
之所以可行,可能是因为该窗口以“ this”形式传递。我已经解决了答案。感谢您指出此错误。
MadisonTrash

8
有没有办法排除外部特定元素?例如,我外面有一个按钮必须打开此元素,因为它触发了这两种方法,所以什么也没有发生。
Žilvinas

5
你能解释一下vnode.context [binding.expression](event); ?
塞纳特SR

1
如何更改此设置,以便触发表达式,而不是触发v-click-outside内部的方法?
raphadko

50

tabindex属性添加到您的组件,以便可以集中精力并执行以下操作:

<template>
    <div
        @focus="handleFocus"
        @focusout="handleFocusOut"
        tabindex="0"
    >
      SOME CONTENT HERE
    </div>
</template>

<script>
export default {    
    methods: {
        handleFocus() {
            // do something here
        },
        handleFocusOut() {
            // do something here
        }
    }
}
</script>

4
哇!我发现这是最短,最干净的解决方案。也是对我而言唯一有效的方法。
马特·科马尼克

3
只需添加此值,将tabindex设置为-1即可在您单击该元素时阻止突出显示框,但是它仍将使div可聚焦。
科林

1
由于某种原因,tabindex -1不会为我隐藏轮廓,因此我只是outline: none;为该元素添加了焦点。
Art3mix

1
我们如何将其应用到可滑动到屏幕上的非帆布侧面导航?我无法给sidenav焦点,除非它被点击,
查尔斯Okwuagwu

1
这绝对是最强大的方法。谢谢!:)
Canet Robern

23

社区中有两个软件包可用于此任务(均已维护):


8
vue-clickaway包完美地解决了我的问题。谢谢
Abdalla Arbab '18

1
那很多物品呢?具有外部点击事件的每个项目都会在每次点击时触发事件。创建对话框时很好,而创建图库时则很糟糕。在非组件时代,我们正在监听来自文档的点击,并检查单击了哪个元素。但是现在很痛苦。
br。

@Julien Le Coupanec我找到了迄今为​​止最好的解决方案!非常感谢您的分享!
曼努埃尔·阿巴斯卡尔

7

这适用于Vue.js 2.5.2:

/**
 * Call a function when a click is detected outside of the
 * current DOM node ( AND its children )
 *
 * Example :
 *
 * <template>
 *   <div v-click-outside="onClickOutside">Hello</div>
 * </template>
 *
 * <script>
 * import clickOutside from '../../../../directives/clickOutside'
 * export default {
 *   directives: {
 *     clickOutside
 *   },
 *   data () {
 *     return {
         showDatePicker: false
 *     }
 *   },
 *   methods: {
 *     onClickOutside (event) {
 *       this.showDatePicker = false
 *     }
 *   }
 * }
 * </script>
 */
export default {
  bind: function (el, binding, vNode) {
    el.__vueClickOutside__ = event => {
      if (!el.contains(event.target)) {
        // call method provided in v-click-outside value
        vNode.context[binding.expression](event)
        event.stopPropagation()
      }
    }
    document.body.addEventListener('click', el.__vueClickOutside__)
  },
  unbind: function (el, binding, vNode) {
    // Remove Event Listeners
    document.removeEventListener('click', el.__vueClickOutside__)
    el.__vueClickOutside__ = null
  }
}

谢谢你的这个例子。在vue 2.6上进行了检查。有一些解决方法,在unbind方法中,您必须通过此方法解决某些问题(您在unbind方法中忘记了body属性):document.body.removeEventListener('click',el .__ vueClickOutside__); 如果不是,它将在每次重新创建组件(刷新页面)之后导致创建多个事件侦听器;
Alexey Shabramov

7
export default {
  bind: function (el, binding, vNode) {
    // Provided expression must evaluate to a function.
    if (typeof binding.value !== 'function') {
      const compName = vNode.context.name
      let warn = `[Vue-click-outside:] provided expression '${binding.expression}' is not a function, but has to be`
      if (compName) { warn += `Found in component '${compName}'` }

      console.warn(warn)
    }
    // Define Handler and cache it on the element
    const bubble = binding.modifiers.bubble
    const handler = (e) => {
      if (bubble || (!el.contains(e.target) && el !== e.target)) {
        binding.value(e)
      }
    }
    el.__vueClickOutside__ = handler

    // add Event Listeners
    document.addEventListener('click', handler)
  },

  unbind: function (el, binding) {
    // Remove Event Listeners
    document.removeEventListener('click', el.__vueClickOutside__)
    el.__vueClickOutside__ = null

  }
}

5

我合并了所有答案(包括来自vue-clickaway的一行),并提出了适用于我的解决方案:

Vue.directive('click-outside', {
    bind(el, binding, vnode) {
        var vm = vnode.context;
        var callback = binding.value;

        el.clickOutsideEvent = function (event) {
            if (!(el == event.target || el.contains(event.target))) {
                return callback.call(vm, event);
            }
        };
        document.body.addEventListener('click', el.clickOutsideEvent);
    },
    unbind(el) {
        document.body.removeEventListener('click', el.clickOutsideEvent);
    }
});

在组件中使用:

<li v-click-outside="closeSearch">
  <!-- your component here -->
</li>

几乎下同@MadisonTrash答案
retrovertigo

3

我已经更新了MadisonTrash的答案以支持Mobile Safari(没有click事件,touchend必须使用它)。它还包含一个检查,以使事件不会因在移动设备上拖动而触发。

Vue.directive('click-outside', {
    bind: function (el, binding, vnode) {
        el.eventSetDrag = function () {
            el.setAttribute('data-dragging', 'yes');
        }
        el.eventClearDrag = function () {
            el.removeAttribute('data-dragging');
        }
        el.eventOnClick = function (event) {
            var dragging = el.getAttribute('data-dragging');
            // Check that the click was outside the el and its children, and wasn't a drag
            if (!(el == event.target || el.contains(event.target)) && !dragging) {
                // call method provided in attribute value
                vnode.context[binding.expression](event);
            }
        };
        document.addEventListener('touchstart', el.eventClearDrag);
        document.addEventListener('touchmove', el.eventSetDrag);
        document.addEventListener('click', el.eventOnClick);
        document.addEventListener('touchend', el.eventOnClick);
    }, unbind: function (el) {
        document.removeEventListener('touchstart', el.eventClearDrag);
        document.removeEventListener('touchmove', el.eventSetDrag);
        document.removeEventListener('click', el.eventOnClick);
        document.removeEventListener('touchend', el.eventOnClick);
        el.removeAttribute('data-dragging');
    },
});

3

我使用以下代码:

显示隐藏按钮

 <a @click.stop="visualSwitch()"> show hide </a>

显示隐藏元素

<div class="dialog-popup" v-if="visualState" @click.stop=""></div>

脚本

data () { return {
    visualState: false,
}},
methods: {
    visualSwitch() {
        this.visualState = !this.visualState;
        if (this.visualState)
            document.addEventListener('click', this.visualState);
        else
            document.removeEventListener('click', this.visualState);
    },
},

更新:删除手表;添加停止传播


2

我讨厌其他功能,所以...这是一个很棒的vue解决方案,没有其他vue方法,只有var

  1. 创建html元素,设置控件和指令
    <p @click="popup = !popup" v-out="popup">

    <div v-if="popup">
       My awesome popup
    </div>
  1. 在数据中创建一个变量
data:{
   popup: false,
}
  1. 添加vue指令。它的
Vue.directive('out', {

    bind: function (el, binding, vNode) {
        const handler = (e) => {
            if (!el.contains(e.target) && el !== e.target) {
                //and here is you toggle var. thats it
                vNode.context[binding.expression] = false
            }
        }
        el.out = handler
        document.addEventListener('click', handler)
    },

    unbind: function (el, binding) {
        document.removeEventListener('click', el.out)
        el.out = null
    }
})


1

您可以像这样为click事件注册两个事件侦听器

document.getElementById("some-area")
        .addEventListener("click", function(e){
        alert("You clicked on the area!");
        e.stopPropagation();// this will stop propagation of this event to upper level
     }
);

document.body.addEventListener("click", 
   function(e) {
           alert("You clicked outside the area!");
         }
);

谢谢。我知道这一点,但是感觉必须在Vue.js中有更好的方法来做到这一点?

好!让一些vue.js天才答案:)
saravanakumar

1
  <button 
    class="dropdown"
    @click.prevent="toggle"
    ref="toggle"
    :class="{'is-active': isActiveEl}"
  >
    Click me
  </button>

  data() {
   return {
     isActiveEl: false
   }
  }, 
  created() {
    window.addEventListener('click', this.close);
  },
  beforeDestroy() {
    window.removeEventListener('click', this.close);
  },
  methods: {
    toggle: function() {
      this.isActiveEl = !this.isActiveEl;
    },
    close(e) {
      if (!this.$refs.toggle.contains(e.target)) {
        this.isActiveEl = false;
      }
    },
  },

谢谢,工作得很好,如果您只需要一次,就不需要额外的库
玛丽安·克鲁斯派(MarianKlühspies)

1

简短的答案:这应该使用“ 自定义指令”完成。

这里有很多很棒的答案,也可以这么说,但是当您开始广泛使用外部点击(尤其是分层或多个排除项)时,我看到的大多数答案都会分解。我写了一篇文章有关媒介,讨论了自定义指令的细微差别,尤其是该指令的实现。它可能无法涵盖所有​​极端情况,但涵盖了我所想到的所有内容。

这将考虑多个绑定,其他元素排除的多个级别,并允许您的处理程序仅管理“业务逻辑”。

这是至少定义部分的代码,请查看文章以获取完整说明。

var handleOutsideClick={}
const OutsideClick = {
  // this directive is run on the bind and unbind hooks
  bind (el, binding, vnode) {
    // Define the function to be called on click, filter the excludes and call the handler
    handleOutsideClick[el.id] = e => {
      e.stopPropagation()
      // extract the handler and exclude from the binding value
      const { handler, exclude } = binding.value
      // set variable to keep track of if the clicked element is in the exclude list
      let clickedOnExcludedEl = false
      // if the target element has no classes, it won't be in the exclude list skip the check
      if (e.target._prevClass !== undefined) {
        // for each exclude name check if it matches any of the target element's classes
        for (const className of exclude) {
          clickedOnExcludedEl = e.target._prevClass.includes(className)
          if (clickedOnExcludedEl) {
            break // once we have found one match, stop looking
          }
        }
      }
      // don't call the handler if our directive element contains the target element
      // or if the element was in the exclude list
      if (!(el.contains(e.target) || clickedOnExcludedEl)) {
        handler()
      }
    }
    // Register our outsideClick handler on the click/touchstart listeners
    document.addEventListener('click', handleOutsideClick[el.id])
    document.addEventListener('touchstart', handleOutsideClick[el.id])
    document.onkeydown = e => {
      //this is an option but may not work right with multiple handlers
      if (e.keyCode === 27) {
        // TODO: there are minor issues when escape is clicked right after open keeping the old target
        handleOutsideClick[el.id](e)
      }
    }
  },
  unbind () {
    // If the element that has v-outside-click is removed, unbind it from listeners
    document.removeEventListener('click', handleOutsideClick[el.id])
    document.removeEventListener('touchstart', handleOutsideClick[el.id])
    document.onkeydown = null //Note that this may not work with multiple listeners
  }
}
export default OutsideClick

1

我使用created()中的函数做了一些稍微不同的方式。

  created() {
      window.addEventListener('click', (e) => {
        if (!this.$el.contains(e.target)){
          this.showMobileNav = false
        }
      })
  },

这样,如果有人在元素外部单击,则在我的情况下,移动导航被隐藏。

希望这可以帮助!


1

这个问题已经有很多答案,而且大多数答案都基于类似的自定义指令思想。这种方法的问题在于,必须将方法函数传递给指令,并且不能像其他事件一样直接编写代码。

我创建了一个vue-on-clickout不同的新程序包。在以下位置查看:

它允许v-on:clickout像其他事件一样进行编写。例如,你可以写

<div v-on:clickout="myField=value" v-on:click="myField=otherValue">...</div>

而且有效。

更新资料

vue-on-clickout 现在支持Vue 3!


0

就像有人在模态外部单击时正在寻找如何隐藏模态一样。由于modal通常具有类modal-wrap或您命名的类的包装器,因此可以放入@click="closeModal"包装器。使用vuejs文档中所述的事件处理,您可以检查单击的目标是在包装器上还是在模式上。

methods: {
  closeModal(e) {
    this.event = function(event) {
      if (event.target.className == 'modal-wrap') {
        // close modal here
        this.$store.commit("catalog/hideModal");
        document.body.removeEventListener("click", this.event);
      }
    }.bind(this);
    document.body.addEventListener("click", this.event);
  },
}
<div class="modal-wrap" @click="closeModal">
  <div class="modal">
    ...
  </div>
<div>


0

@Denis Danilenko解决方案为我工作,这是我所做的事情:顺便说一句,我在这里和Bootstrap4一起使用VueJS CLI3和NuxtJS,但在没有NuxtJS的情况下也可以在VueJS上工作:

<div
    class="dropdown ml-auto"
    :class="showDropdown ? null : 'show'">
    <a 
        href="#" 
        class="nav-link" 
        role="button" 
        id="dropdownMenuLink" 
        data-toggle="dropdown" 
        aria-haspopup="true" 
        aria-expanded="false"
        @click="showDropdown = !showDropdown"
        @blur="unfocused">
        <i class="fas fa-bars"></i>
    </a>
    <div 
        class="dropdown-menu dropdown-menu-right" 
        aria-labelledby="dropdownMenuLink"
        :class="showDropdown ? null : 'show'">
        <nuxt-link class="dropdown-item" to="/contact">Contact</nuxt-link>
        <nuxt-link class="dropdown-item" to="/faq">FAQ</nuxt-link>
    </div>
</div>
export default {
    data() {
        return {
            showDropdown: true
        }
    },
    methods: {
    unfocused() {
        this.showDropdown = !this.showDropdown;
    }
  }
}

0

您可以从指令发出自定义的本地javascript事件。使用node.dispatchEvent创建一个从节点调度事件的指令

let handleOutsideClick;
Vue.directive('out-click', {
    bind (el, binding, vnode) {

        handleOutsideClick = (e) => {
            e.stopPropagation()
            const handler = binding.value

            if (el.contains(e.target)) {
                el.dispatchEvent(new Event('out-click')) <-- HERE
            }
        }

        document.addEventListener('click', handleOutsideClick)
        document.addEventListener('touchstart', handleOutsideClick)
    },
    unbind () {
        document.removeEventListener('click', handleOutsideClick)
        document.removeEventListener('touchstart', handleOutsideClick)
    }
})

可以这样使用

h3( v-out-click @click="$emit('show')" @out-click="$emit('hide')" )

0

我在主体的末尾创建一个div,如下所示:

<div v-if="isPopup" class="outside" v-on:click="away()"></div>

其中.outside是:

.outside {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0px;
  left: 0px;
}

away()是Vue实例中的方法:

away() {
 this.isPopup = false;
}

简单,效果很好。


0

如果您的组件在根元素中包含多个元素,则可以使用带有布尔值的“ It just works™”解决方案。

<template>
  <div @click="clickInside"></div>
<template>
<script>
export default {
  name: "MyComponent",
  methods: {
    clickInside() {
      this.inside = true;
      setTimeout(() => (this.inside = false), 0);
    },
    clickOutside() {
      if (this.inside) return;
      // handle outside state from here
    }
  },
  created() {
    this.__handlerRef__ = this.clickOutside.bind(this);
    document.body.addEventListener("click", this.__handlerRef__);
  },
  destroyed() {
    document.body.removeEventListener("click", this.__handlerRef__);
  },
};
</script>

0

使用此程序包vue-click-outside

它简单可靠,目前已被许多其他软件包使用。您还可以通过仅在必需的组件中调用包来减小javascript包的大小(请参见下面的示例)。

npm install vue-click-outside

用法:

<template>
  <div>
    <div v-click-outside="hide" @click="toggle">Toggle</div>
    <div v-show="opened">Popup item</div>
  </div>
</template>

<script>
import ClickOutside from 'vue-click-outside'

export default {
  data () {
    return {
      opened: false
    }
  },

  methods: {
    toggle () {
      this.opened = true
    },

    hide () {
      this.opened = false
    }
  },

  mounted () {
    // prevent click outside event with popupItem.
    this.popupItem = this.$el
  },

  // do not forget this section
  directives: {
    ClickOutside
  }
}
</script>


0

您可以创建处理外部点击的新组件

Vue.component('click-outside', {
  created: function () {
    document.body.addEventListener('click', (e) => {
       if (!this.$el.contains(e.target)) {
            this.$emit('clickOutside');
           
        })
  },
  template: `
    <template>
        <div>
            <slot/>
        </div>
    </template>
`
})

并使用此组件:

<template>
    <click-outside @clickOutside="console.log('Click outside Worked!')">
      <div> Your code...</div>
    </click-outside>
</template>

-1

人们经常想知道用户是否离开根组件(与任何级别的组件一起使用)

Vue({
  data: {},
  methods: {
    unfocused : function() {
      alert('good bye');
    }
  }
})
<template>
  <div tabindex="1" @blur="unfocused">Content inside</div>
</template>


-1

我有一个处理切换下拉菜单的解决方案:

export default {
data() {
  return {
    dropdownOpen: false,
  }
},
methods: {
      showDropdown() {
        console.log('clicked...')
        this.dropdownOpen = !this.dropdownOpen
        // this will control show or hide the menu
        $(document).one('click.status', (e)=> {
          this.dropdownOpen = false
        })
      },
}

-1

我正在使用这个包: https //www.npmjs.com/package/vue-click-outside

这对我来说可以

HTML:

<div class="__card-content" v-click-outside="hide" v-if="cardContentVisible">
    <div class="card-header">
        <input class="subject-input" placeholder="Subject" name=""/>
    </div>
    <div class="card-body">
        <textarea class="conversation-textarea" placeholder="Start a conversation"></textarea>
    </div>
</div>

我的脚本代码:

import ClickOutside from 'vue-click-outside'
export default
{
    data(){
        return {
            cardContentVisible:false
        }
    },
    created()
    {
    },
    methods:
        {
            openCardContent()
            {
                this.cardContentVisible = true;
            }, hide () {
            this.cardContentVisible = false
                }
        },
    directives: {
            ClickOutside
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.