Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue dynamic component event bindings

I have a dynamic component that is resolved and bound on runtime using the documented dynamic component syntax;

<div class="field">
    <component v-if="component" :is="component" @valueUpdated="onUpdate($event)"></component>
</div>

Decided using a prop assigned to on mounting.

For whatever reason, when the child component, rendered dynamically, emits an event this.$emit('eventName', /*someData*/) the parent does not seem to be able to hear it. Is the approach used in standard components applicable to those rendered dynamically? Props seem to work, so maybe I am not doing something correctly?

like image 378
Daniel Park Avatar asked Nov 29 '16 06:11

Daniel Park


1 Answers

yeah you can use props with dynamic components it's just you need to use lowercase hyphenated (kebab-case) names for the html attribute, i.e.

<component v-if="component" :is="component" @value-updated="onUpdate"></component>

  Vue.component('foo', {
  template: `
    <div>
          <button @click="$emit('value-updated', { bar: 'baz' })">pass data</button
        </div>
    `
});

new Vue({
    el: '#app',
    data: {
        currentComponent: 'foo',
        output: {},
    },
    methods: {
        onUpdate (payload) {
            this.output = payload
        }
    }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
    <component v-if="currentComponent" :is="currentComponent" @value-updated="onUpdate"></component>
    <pre>{{ output }}</pre>
</div>
like image 64
GuyC Avatar answered Oct 21 '22 18:10

GuyC