Creation:2026-06-22Last update:2026-06-22
将此文档参考到您的 AI 助手ChatGPTClaudeDeepSeekGoogle AI modeGeminiPerplexityMistralGrok
使用您最喜欢的AI助手总结文档,并引用此页面和AI提供商
版本历史
- "添加 usePathname 实用程序"v10.0.02026/6/23
- "初始化历史记录"v8.2.02026/6/22
此页面的内容已使用 AI 翻译。
查看英文原文的最新版本Edit this doc
If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy
Copy doc Markdown to clipboard
Svelte 集成:usePathname 文档
usePathname 函数以 Svelte 的 Readable<string> store 形式返回去除了 locale 段的当前浏览器路径名(pathname)。这对于构建支持 locale 的导航非常有用——例如,判断哪个导航项是激活状态的——而无需手动去除 locale 前缀。
在 Svelte 中导入 usePathname
typescript
复制代码
复制代码到剪贴板
import { usePathname } from "svelte-intlayer";概述
usePathname 创建一个 Svelte readable store,它读取 window.location.pathname,通过 getPathWithoutLocale 去除 locale 前缀,并在浏览器触发 popstate 事件(后退/前进导航)时发出新值。在组件中使用 $ 语法来订阅。
用法
src/components/NavItem.svelte
复制代码
复制代码到剪贴板
<script lang="ts"> import { usePathname } from "svelte-intlayer"; export let href: string; export let label: string; const pathname = usePathname();</script><a {href} aria-current={$pathname === href ? "page" : undefined}> {label}</a>返回值
显示表格的所有内容
在弹窗中打开表格以清晰地查看所有数据
| 类型 | 描述 |
|---|---|
Readable<string> | 包含不带 locale 前缀的当前路径名(pathname)的 Svelte readable store。 |
行为
- 去除 Locale:移除开头的 locale 段(例如
/zh/dashboard→/dashboard)。 - 响应式:在每次
popstate事件(浏览器的后退 / 前进导航)触发时发出新值。 - SSR 安全:在
window不可用时返回""。 - 清理(Cleanup):当最后一个订阅者取消订阅时,会自动移除
popstate监听器。
示例
src/components/Sidebar.svelte
复制代码
复制代码到剪贴板
<script lang="ts"> import { usePathname } from "svelte-intlayer"; const links = [ { href: "/dashboard", label: "仪表盘" }, { href: "/settings", label: "设置" }, ]; const pathname = usePathname();</script><nav> {#each links as link} <a href={link.href} style:font-weight={$pathname === link.href ? "bold" : "normal"} > {link.label} </a> {/each}</nav>相关阅读
useLocale— 当前 locale + locale 切换器getPathWithoutLocale— 该 hook 所使用的底层实用程序