Juliver Galleto
Juliver Galleto

Reputation: 9037

Click event on vue component that was pass down to slot

I have this two components part of my custom slider plugin, component 1 will be the wrapper and the component 2 will pass down to component 1 slot:

comp1.vue:

<template>
    <div id="sliderwrapper">
        <slot></slot>
    </div>
</template>

comp2.vue:

<template>
    <div class="slider">
        <slot></slot>
    </div>
</template>

Now, in my Vue app, I do

<sliderwrapper>
    <sliderbox @click="slideritem(item.title)" v-for="(item,index) in slideritems" :key="index">
        <p>{{ item.title }}</p>
    </sliderbox>
</sliderwrapper>

import sliderwrapper from './comp1.vue';
import sliderbox from './comp2.vue';

export default{
    components : [ sliderwrapper, sliderbox ],
    data() {
        return {
            slideritems : [
                { title : 'title 1' },
                { title : 'title 2' },
                { title : 'title 3' },
            ]
        }
    },
    methods : {
        slideritem(title){
            alert(title);
        }
    }
}

Unfortunately the click event on component 2 <sliderbox> is not working nor triggering, something like event was not attached.

Any ideas?

Upvotes: 4

Views: 2190

Answers (2)

skirtle
skirtle

Reputation: 29112

Using @click on a component will only listen for a click event explicitly emitted by that component using $emit. It won't listen for the DOM event.

To listen for the native event you'd need to use @click.native instead.

See:

https://v2.vuejs.org/v2/guide/components-custom-events.html#Binding-Native-Events-to-Components

Upvotes: 4

navanjr
navanjr

Reputation: 598

v-on:click.native="slideritem(item.title)"

should do it.

Upvotes: 1

Related Questions