[Vuejs]-How do I use JavaScript to dynamically add Vue components

0👍

It’s not clear whether your list item components have special functionality or they’re just lots of <li>s. If it’s just data, then: rather than moving your list items out into separate Vue components, you may be able to achieve a better result with simple Javascript functions. For example:

import { apiSublist } from './sublists'
...
    list: [
        {
            title: "API",
            open: false,
            sublist: apiSublist()
        },
    ]
function apiSublist() {
    return ['Option 1', 'Option 2', 'Option 3']
}

You could, of course, move the entire “API” object into a function and modularize it even more.

If your list must use Vue components, then this is a perfect case for generic components.

// Generic component
<template>
    <ul v-show="list.open" class="list-item">
        // Assumes that every member of the sublist is a string component name
        <component :is="item" class="sub-items"
            v-for="(item,index) in list.sublist" :key="index" />
    </ul>
</template>

Leave a comment