wtf512
wtf512

Reputation: 4738

Vue dynamic component, how to handle different emit and pass props and replace different slot?

Just know some basic knowledge about dynamic components, but what if the component is complex or different from each other, how to handle the emit, props and slot in parent?

Suppoese I got 3 components:

Component 1

<template>
    <div class="app-container">
        <spinner :color="this.colore"></spinner>
        <slot></slot>
    </div>
</template>

It's about loading, and I need to pass a prop "color" and some buttons in slot.

Component 2

<template>
    <div class="app-container">
        <form>
            ......
            <button @click="onClick"></buttom>
        </form>
    </div>
</template>

method: {
    onClick: function () {
        this.$emit('form-submit');
    }
}

This component doesn't hold any props or slot, but there is an emit when button clicked.

Component 3

<template>
    <div class="app-container">
        <header>
            <slot name="header"></slot>
        </header>
        <main>
            <slot></slot>
        </main>
        <footer>
            <slot name="footer"></slot>
        </footer>
    </div>
</template>

This component is just about to display info. But there are 3 different slots.

And finally, in parent view, if I want to use dynamic component, what is the right way to to?

<template>
    <div class="homepage">
        <header></header>
        <keep-alive>
            <component :is="currentComp"/>
        </keep-alive>
    </div>
</template>

@Component({
    components: {
        Component1,
        Component2,
        Component3,
    },
})

export default class HomepageView extends Vue {

    public currentComp: VueConstructor = Component1;
    
    public switchToComp1: void {
        currentComp = Component1;
    }

    public switchToComp2: void {
        currentComp = Component2;
    }

    public switchToComp3: void {
        currentComp = Component3;
    }

}

I mean both comp1 and comp3 need to pass props or replace slots. The switchToCompX methods, how can I complement it in the right way? And how to receive emit from comp2 since only comp2 will emit.

Upvotes: 0

Views: 880

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37923

Both props and events can be passed using objects so you can keep that objects in data and switch the content same way you switch active component

<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>
<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>

Slots must be defined in the template so only way is probably to define them all and use v-if to activate only those needed by active component...

Anyway it would be much easier to use v-if instead of dynamic component in this simple case

Upvotes: 1

Related Questions