简体   繁体   中英

Add dynamically components in vue.js not working

I try to add dynamically component. This component set into props. I not register components into components:{} section, because I don't now how many components and their name will be send from props. I use ES6 syntax, where import js modules not work into ready(){} section. My code:

 let Child = Vue.extend({ data() { return { msg: 'CHILDREN' } }, template: '<div class="c-child">component {{msg}}</div>' }) let Parent = Vue.extend({ props: { component: '' }, data() { return { msg: 'PARENT' } }, template: '<div class="c-parent">from component- {{msg}}<br><component :is="component"/></div>', }) // register Vue.component('parent-component', Parent) // create a root instance let vue = new Vue({ el: '#root' }) 
 .c-parent { border: 1px solid red; padding: 10px; } .c-child { border: 1px solid green; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.common.js"></script> <div id="root"> <parent-component :component="Child"></parent-component> </div> 

Dynamic component not render:

<component :is="component"/>

PS This code work on jsfiddle - open link

You need to parse the interpreted component name to :is="" component, defining them the following way should work:

import GroupsGrid from './../../components/groups'
import RolesGrid from './../../components/roles'
import MainTabs from './../../components/main-tabs.vue' // <-- this component will be render other components

    data: {
        tabs: {
            'GroupsGrid': 'groups-grid',
            'RolesGrid': 'roles-grid'
        }
    },

And still used like this

<component :is="tabs.GroupsGrid"></component>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM