0

I have a 3rd party component <third-party-component /> which accepts following event:

onAdd, onRemove, onUpdate

I want to create a wrapper component around it and want to pass these events dynamically so that can handle the response in wrapper component, something like wrapper.js

<template>
    <div class="my-wrapper">
        <third-party-component />
    </div>
<template>

using-wrapper.js

<template>
    <div>
        ...
        <wrapper @onAdd="add" @onRemove="remove"></wrapper>
        ...
    </div>
</template>
<script>
export default {
    methods: {
        onAdd() {
            console.log('on add in using-wrapper.js');
        },
        onRemove() {
            console.log('on remove in using-wrapper.js');
        }
    }
}
</script>
coure2011
  • 40,286
  • 83
  • 216
  • 349

2 Answers2

1

You can pass all attributes and listeners by binding them using v-bind and v-on

You also need to set inheritAttrs to false https://v2.vuejs.org/v2/api/#inheritAttrs

<template>
    <div class="my-wrapper">
        <third-party-component v-bind="$attrs" v-on="$listeners"/>
    </div>
<template>

using-wrapper.js

<template>
    <div>
        ...
        <wrapper @onAdd="add" @onRemove="remove"></wrapper>
        ...
    </div>
</template>
<script>
export default {
    inheritAttrs: false,
    methods: {
        onAdd() {
            console.log('on add in using-wrapper.js');
        },
        onRemove() {
            console.log('on remove in using-wrapper.js');
        }
    }
}
</script>
tony19
  • 125,647
  • 18
  • 229
  • 307
Daniel
  • 34,125
  • 17
  • 102
  • 150
0

Well on "wrapper" you will need to create 3 methods that listen and get triggered on "third-party-component".

<template>
<div class="my-wrapper">
    <third-party-component @onAdd="wrapperAdd" @onRemove="wrapperRemove" @onUpdate="wrapperUpdate" />
</div>

<script>
export default {
   methods:{
     wrapperAdd(){
       this.$emit("onAdd",{obj that will get to the parent});
     }
   }
}

I made only 1 method because the other 2 are similar.

  • I wouldn't bother creating methods; the whole thing can be inline ~ `@onAdd="$emit('onAdd', ...arguments)"`, etc – Phil Jun 25 '18 at 07:02
  • if he need to do there more than emit an event , he will need to do a method and on my personal opinion it is better to have less javascript on template. – Munteanu Petrisor Jun 25 '18 at 07:28