17

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?

1 Answer 1

20

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>

Sign up to request clarification or add additional context in comments.

4 Comments

updated answer - not sure why I added the prop example as not relevant here - just make sure you use kebab case and emit the event name: this.$emit('value-updated', { foo: 'bar' })
Ah I see. So there is a translation between Camel and Kebab? About to try, so will mark as answer when try it out
could you please explain why there is v-if="component" in component ?
@KickButtowski I tweaked that to be v-if="currentComponent" which hopefully makes a little more sense in the example above, i.e. it tests there is a currentComponent string before trying to instantiate it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.