【问题标题】:How to add an "active" class to navbar in sveltekit?如何在 sveltekit 中向导航栏添加“活动”类?
【发布时间】:2022-03-01 00:09:07
【问题描述】:

我正在尝试在路由更改时设置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 sveltekit


【解决方案1】:

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

<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>

【讨论】:

    【解决方案2】:
    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      相关资源
      最近更新 更多