yaminncco / vue-sidebar-menu

A Vue.js Sidebar Menu Component
MIT License
654 stars 193 forks source link

Dynamic routing for sub navigation items using Inertia #269

Closed peter-tell closed 9 months ago

peter-tell commented 9 months ago

For example, I have a route in Laravel that looks like this:

Route::get('/my-route/{tab?}', [MyControllerController::class, 'index'])->name('my.route');

My menu config looks like this:

const menu = [
    {
        header: 'Main Navigation',
        hiddenOnCollapse: true,
    },
    {
        href: '/dashboard',
        title: 'Dashboard',
        icon: { element: HomeIcon }
    },
    {
        title: 'My Route',
        icon: { element: MegaphoneIcon },
       topNoLink: '/my-route',
        child: [
            {
                href: '/my-route',
                title: 'My Route',
            },
        ],
    },
];

I'm also using the following link-component-name:

const customLink = {
    props: ['item'],
    render() {
        const isActive = this.$page.url.startsWith(this.item.href) || (this.item.topNoLink && this.$page.url.startsWith(this.item.topNoLink));
        const linkProps = {
            class: isActive ? 'vsm--link_active' : '',
        };
        return h(this.item.href ? Link : 'a', linkProps, this.$slots.default());
    },
    watch: {
        '$page.url'() {
            this.onRouteChange()
        }
    },
    inject: ['onRouteChange']
}

My goal is that if someone visits any of these: /my-route /my-route/anything

This navigation item is expanded and each of the active states on the parent and child are set. Using the customLink referenced above I'm able to set the active state, but the navigation item is not expanded.

yaminncco commented 9 months ago

In v5.3.0 you can use isActive property to set the active state

{
    title: 'My Route',
    icon: { element: MegaphoneIcon },
    child: [
        {
            href: '/my-route',
            title: 'My Route',
            isActive: (item) => page.url.startsWith(item.href),
        },
    ],
},
peter-tell commented 9 months ago

Brilliant thank you! For anyone referencing this task in the future I ended up with:

isActive: (item) => { return router.page.url.startsWith(item.href); },

Since I'm using Inertia