[Vuejs]-Trigger click on vuejs slotted element within parent component

0👍

You can try with div :

Vue.component('AppPrimaryOptions', {
  template: `
  <div class="options">
    <slot />
  </div>
  `
})

Vue.component('AppPrimaryOptionsOption', {
  template: `
  <div class="option">
    <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>

0👍

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.

Leave a comment