0

只知道一些动态组件的基础知识,但是如果组件比较复杂或者相互不同,那么如何处理parent中的emit、props和slot呢?

假设我有 3 个组件:

组件 1

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

这是关于加载的,我需要在插槽中传递一个道具“颜色”和一些按钮。

组件 2

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

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

该组件不包含任何道具或插槽,但单击按钮时会发出。

组件 3

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

该组件即将显示信息。但是有3个不同的插槽。

最后,在父视图中,如果我想使用动态组件,正确的方法是什么?

<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;
    }

}

我的意思是 comp1 和 comp3 都需要传递道具或替换插槽。switchToCompX方法,我怎样才能以正确的方式补充它?以及如何从 comp2 接收发射,因为只有 comp2 会发射。

4

1 回答 1

1

道具和事件都可以使用对象传递,因此您可以保留该对象并以data与切换活动组件相同的方式切换内容

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

插槽必须在模板中定义,因此唯一的方法可能是将它们全部定义并用于v-if仅激活活动组件所需的那些......

v-if无论如何,在这种简单的情况下,它会比动态组件更容易使用

于 2020-09-14T11:43:04.310 回答