VueJS - 动态加载 child 个组件

VueJS - Load child components dynamically

我正在尝试弄清楚如何从 Laravel 的 blade 模板

中有条件地加载 sub/child 组件
  1. 我有一个主容器,正在从 blade:

    调用

    <structure-container view='menu-index'></structure-container>

  2. 这里是StructureContainer.vue

    <template>
    <div>
        //I can have if-else statement here by "view", but looking for a better solution
        <menu-index></menu-index>
    </div>
    

    export default{
        components: {
            'menu-index': require('./menu/IndexComponent.vue'),
            'test': require('./menu/TestComponent.vue'),
        },
        props: ['view']
    }
    

如您所见,我有两个 child 组件:menu-index & 测试。我想从 blade 传递参数并显示相应的组件。我可以避免 if-else 语句吗?应该有更好的方法来做到这一点

您可以简单地将组件名称动态绑定到 is 属性(使用 v-bind:is:is),即:

<div>
    <component :is="view"></component >
</div>

真正令人敬畏的是 <component> 容器是反应式的,您可以动态地 load/unload/change 即时组件。这有多棒? :)

有关更多信息,我鼓励您阅读 documentation on dynamic components on the official docs