I've seen this answered many times where the goal was for the child component to respond to a click event, but I want the slotted element defined in the parent to manage the click event which should be within the scope of the parent. I don't want the child to manage the click because the child is merely to have consistent formatting. The click action will be unique to every use of the child component. As it stands, clicking the slotted app-primary-options-option element does not trigger the onClick event.
<template>
<app-primary-options>
<app-primary-options-option
v-for="layer in layers"
:key="layer.name"
:value="layer.name"
@click="onClick(layer.name)"
>
{{ layer.longText }}
</app-primary-options-option>
</app-primary-options>
</template>
<script>
import AppPrimaryOptions from '../selectors/PrimaryOptions.vue'
import AppPrimaryOptionsOption from '../selectors/PrimaryOptionsOption.vue'
export default {
methods: {
onClick () {
console.log('Clicked')
}
}
}
</script>
AppPrimaryOptions child:
<template>
<div >
<slot />
</div>
</template>
AppPrimaryOptionsOption child:
<template>
<div >
<slot />
</div>
</template>
CodePudding user response:
You can try with div :
Vue.component('AppPrimaryOptions', {
template: `
<div >
<slot />
</div>
`
})
Vue.component('AppPrimaryOptionsOption', {
template: `
<div >
<slot />
</div>
`
})
new Vue({
el: "#demo",
methods: {
onClick (l) {
console.log('Clicked', l)
}
},
data() {
return {
layers: [{name: 'a', longText: 'aaa'}, {name: 'b', longText: 'bbb'}]
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<app-primary-options>
<app-primary-options-option
v-for="layer in layers"
:key="layer.name"
:value="layer.name"
>
<div @click="onClick(layer.name)">{{ layer.longText }}</div>
</app-primary-options-option>
</app-primary-options>
</div>
CodePudding user response:
From VueJs:
Event listeners passed to a component with v-on are by default only triggered by emitting an event with this.$emit. To add a native DOM listener to the child component's root element instead, the .native modifier can be used
<app-primary-options>
<app-primary-options-option
v-for="layer in layers"
:key="layer.name"
:value="layer.name"
@click.native="onClick(layer.name)"
>
{{ layer.longText }}
</app-primary-options-option>
</app-primary-options>
Incidently, this is provided on the VueJS 3 migration documentation, as the native modifier was removed with this behavior now default.
