如何在 sveltekit 中向导航栏添加“活动”类?

cho*_*ovy 7 svelte 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>

Run Code Online (Sandbox Code Playgroud)

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

Geo*_*ich 16

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

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

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

    $: getPath($page.url.pathname);
</script>
Run Code Online (Sandbox Code Playgroud)

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

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

    $: path = $page.url.pathname;
</script>
Run Code Online (Sandbox Code Playgroud)