Vue.js - Stop propagation for multiple event handlers

家住魔仙堡 提交于 2020-06-27 04:08:21

问题


I have a component that emits an showSelection event on click but also retains the click event handler given to it by its parent.

<template>
    <section class="base-input peudo-select">
        <input 
            v-bind="$attrs"
            type="text"
            readonly
            v-on="listeners"
            @dblclick.prevent.stop
        />
    </section>
</template>

<script>
export default {
    ...
    computed:{
        listeners(){
            return {
                ...this.$listeners,
                input: event => this.$emit('input', event.target.value),
                click: [
                    this.$listeners.click, // Always put the parent given handler first.
                    event => this.$emit('showSelection', event),
                ],
            }
        }
    }
    ...
};
</script>

And on its parent component, i have this.

<template>
    <section class="main-page">
        <pseudo-select-input
            tooltip="How would you like to pay?"
            placeholder="Source of Fund"
            @click="selectInputClicked($event)"
            @showSelection="showSelection"
        />
    </section>
</template>

<script>
export default {
    ...
    methods: {
        selectInputClicked(e) {
            console.log('stopping propagation');
            e.stopPropagation();
        },
        showSelection() {
            console.log('starting selection');
        },
    },
    ...
};
</script>

When try to run the code, both logs are are shown even when selectInputClicked tried stopping the propagation.

I'm well aware of event.stop but I don't want it to always stop the propagation. I will be having conditions whether it should stop propagation (e.g. a previous input is empty).

No, I don't need to do click.native since i'm "tunneling" the component's event listeners to the input element (see computed->listeners and v-on="listeners").

See fiddle here

The fiddle is not exactly the same as above but it has the same idea.

Update #1:

Throwing an exception on the first handler stops the propagation to the next. For obvious reasons. it is not good enough. I'll save it as a last resort.

来源:https://stackoverflow.com/questions/62079210/vue-js-stop-propagation-for-multiple-event-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!