元素之外点击指令

     directives: {
            clickoutside: {
                bind(el, binding, vnode) {
                    function documentHandler(e) {
                        var reg = RegExp(vnode.context.popupId);

                        // 这里判断点击的元素是否是本身,是本身,则返回
                        if (el.contains(e.target) || (vnode.context.popupId && reg.test(e.target.className))) {
                            return false;
                        }
                        // 判断指令中是否绑定了函数
                        if (binding.expression) {
                            // 如果绑定了函数 则调用那个函数,此处binding.value就是handleClose方法
                            binding.value(e);
                        }
                    }
                    // 给当前元素绑定个私有变量,方便在unbind中可以解除事件监听
                    el.__vueClickOutside__ = documentHandler;
                    document.addEventListener('touchstart', documentHandler);
                },
                update() { },
                unbind(el, binding) {
                    // 解除事件监听
                    document.removeEventListener('touchstart', el.__vueClickOutside__);
                    delete el.__vueClickOutside__;
                }
            }
        },
//元素上绑定
<div class="md-popup-item" v-show="isPopupItemShow" v-clickoutside="onOutClose">
                <slot>aaaaaaa</slot>
            </div>
// 绑定的事件
      onOutClose() {
                this.outClickCose && this.value && this.$_onHidePopup();
            },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容