Skip to content

Instantly share code, notes, and snippets.

@zhuping
Last active July 6, 2020 07:28
Show Gist options
  • Save zhuping/06114d19cbddddec3ec3ccbe03c3190c to your computer and use it in GitHub Desktop.
Save zhuping/06114d19cbddddec3ec3ccbe03c3190c to your computer and use it in GitHub Desktop.
vue 劫持所有 click 事件
let captureContexts = [];
const eventTypes = [ 'click' ];

function delegateBehavior(context) {
    if (context.$el) {
        context.$el.setAttribute('vue-uid', context._uid);
    }

    if (context.$root.$el && !context.$root.$el._isBindDelegate) {
        eventTypes.forEach(eventType => {
            context.$root.$el.addEventListener(eventType, e => {
                captureEvent(e, captureContexts, eventType);
            }, true);
        });

        context.$root.$el._isBindDelegate = true;
    }
}

function captureEvent(e, contexts, eventType) {
    let els = contexts.map(context => context.$el);
    let currentEle = e.target;
    while(currentEle) {
        let index = els.indexOf(currentEle);
        if (index > -1) {
            console.log(e)
            // console.log('target', e.target);
            // console.log('currentTarget', e.currentTarget);
            break;
        }
        currentEle = currentEle.parentNode;
    }
}

Vue.mixin({
    mounted() {
        this.$nextTick(() => {
            captureContexts.push(this);
            delegateBehavior(this);
        });
    }
});

https://www.zhihu.com/question/290066361/answer/486336434

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment