如何在 sveltekit 的导航栏中添加 "active" class?

How to add an "active" class to navbar in sveltekit?

我正在尝试在路线更改时设置 path,但它没有更新:

<script>
    import { page } from '$app/stores';
    let path;

    function getPath() {
        path = $page.url.pathname;
        console.log(path);
    }

    $: $page.url.pathname;
    $: getPath();
</script>

<aside>
    <nav>
        <ul>
            <li class={path === '/' ? 'active' : ''}>
                <a href="/"><img src="/icons/compass.svg" alt="" border="0" />Dashboard</a>
            </li>
            <li class={path === '/messages' ? 'active' : ''}>
                <a href="/messages"><img src="/icons/messages.svg" alt="" border="0" /> Messages</a>
            </li>
        </ul>
    </nav>
</aside>

<style>
    nav li.active a {
        color: #fff;
    }
</style>

当我在浏览器中更改路线时,这不会更新。

这是因为 Svelte 不知道 re-run getPath() 函数。要解决此问题,您可以将路径名作为参数传递,以便 Svelte 在路径更改时知道 re-run 函数。

<script>
    import { page } from '$app/stores';
    let path;

    function getPath(currentPath) {
        path = currentPath;
        console.log(path);
    }

    $: getPath($page.url.pathname);
</script>

如果您只更新 path 变量,您也可以将其简化为根本不使用函数。

<script>
    import { page } from '$app/stores';
    let path;

    $: path = $page.url.pathname;
</script>
let dashboardActive = false;
if(window.location.pathname == '/dashboard'){
    dashboardActive = true;
}

<a class="mainmenuNew" href="/dashboard" >
    {#if dashboardActive}
        <span class="mainmenuImg"><img class='icnImg' src="/leftmenu/dashboard-active.png"></span>
        <span class="mainmenutext activemenutxt" >Dashboard</span>
    {:else}
        <span class="mainmenuImg"><img class='icnImg' src="/leftmenu/dashboard.png"></span>
        <span class="mainmenutext" >Dashboard</span>
    {/if}
    <div style="clear:both;"></div>
</a>