[Vuejs]-Is it in any way possible to add an html elelment to a computed property?

0👍

When I run into things like this, I always find it works out better to abstract things a little and keep the parent neater. So, instead of putting lots of logic into the template, try to put as much of it into the original list, and additional components.

In this case I’d probably create a component to display a single link, and do something like this. It keeps everything cleaner, and makes it easier to make further changes in the future.

In this example I’m using Vue 3 and script setup as that’s my default, but the idea is the same in Vue 2.

// navigation-menu.vue
<template>
    <nav>
        <ul>
            <navigation-item v-for="link in links" v-bind="link" />
        </ul>
    </nav>
</template>

<script setup>
// ... Import navigation-item

const links = [
    {
        label: 'Link 1',
    },
    {
        label: 'Link 2',
        count: 5,
    },
    {
        label: 'Link 3',
    },
];
</script>
// navigation-item.vue
<template>
    <li>
        {{ label }}

        <span v-if="count">{{ count }}</span>
    </li>
</template>

<script setup>
defineProps({
    /**
     * The label to display on the menu item.
     */
    label: {
        type: String,
        required: true,
    },

    /**
     * A notification-style count to display beside the menu item.
     */
    count: {
        type: Number,
        default: null,
    },
});
</script>

Leave a comment