问题
I'm trying to figure out how to conditionally load sub/child component from Laravel's blade template
I have a main container, which is being called from the blade:
<structure-container view='menu-index'></structure-container>
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