VueJS - Load child components dynamically

∥☆過路亽.° 提交于 2019-12-25 00:21:01

问题


I'm trying to figure out how to conditionally load sub/child component from Laravel's blade template

  1. I have a main container, which is being called from the blade:

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

  2. Here is the 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']
    }
    

As you can see I have two child components: menu-index & test. I want to pass the parameter from blade and display the corresponding component. Can I avoid if-else statements? there should be a better way to do this


回答1:


You can simply bind the component name dynamically to the is property (using v-bind:is or :is), i.e.:

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

The really awesome thing about this is that the <component> container is reactive, and you can dynamically load/unload/change the components on-the-fly. How awesome is that? :)

For more information, I encourage you to read up the documentation on dynamic components on the official docs.



来源:https://stackoverflow.com/questions/45613935/vuejs-load-child-components-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!