useMovkI18n() 屏蔽了 i18n 开关两种状态的差异。layer 内的页面、导航、搜索与组件都通过它选择 locale 对应的集合与路径,自定义组件也应如此,而不是直接调用 useI18n()。
用法
app/components/DocsLink.vue
<script setup lang="ts">
const { t, localePath, docsRoot } = useMovkI18n()
</script>
<template>
<NuxtLink :to="localePath('/releases')">
{{ t('docs.overview') }}
</NuxtLink>
<NuxtLink :to="`${docsRoot}/getting-started`">
Docs
</NuxtLink>
</template>
签名
function useMovkI18n(): MovkI18n
interface MovkLocale {
code: string
name: string
language?: string
dir?: 'ltr' | 'rtl'
}
返回值
| 名称 | 类型 | 说明 |
|---|---|---|
isEnabled | boolean | 消费方是否启用了 @nuxtjs/i18n |
locale | Ref<string> | 当前语言代码 |
defaultLocale | string | 默认语言代码 |
locales | MovkLocale[] | 构建期过滤后的有效语言列表;未启用 i18n 时为空数组 |
t | (key: string, params?: Record<string, string | number>) => string | 读取内置翻译,{name} 形式的占位符由 params 替换;找不到 key 时原样返回 |
localePath | (path: string) => string | 为站内路径加当前语言前缀;未启用 i18n 时原样返回 |
switchLocalePath | (code?: string) => string | 当前页面在目标语言下的路径;未启用 i18n 时返回空字符串 |
docsRoot | ComputedRef<string> | 当前语言的文档根路径,默认语言为 /docs,其余为 /{locale}/docs |
docsCollection | ComputedRef<string> | 当前语言的文档集合名,默认语言为 docs,其余为 docs_{code} |
landingCollection | ComputedRef<string> | 落地页集合名 |
releasesCollection | ComputedRef<string> | 版本发布页集合名 |
templatesCollection | ComputedRef<string> | 案例页集合名 |
集合名中的 - 会替换为 _,例如 zh-TW 对应 docs_zh_TW。
两种模式
- 启用
@nuxtjs/i18n:locale、t、localePath、switchLocalePath直接委托给 Nuxt i18n,locales来自 layer 过滤后的runtimeConfig.public.movkDocs.filteredLocales。 - 未启用:语言固定为
appConfig.i18n.locale(默认zh-CN),t读取该语言的内置翻译,路由不做本地化。
示例
按当前语言查询文档集合:
<script setup lang="ts">
const { locale, docsCollection } = useMovkI18n()
const { data: pages } = await useAsyncData(
() => `latest-pages-${locale.value}`,
() => queryCollection(docsCollection.value as 'docs').select('title', 'path').limit(5).all()
)
</script>
useAsyncData 的 key 要包含 locale,否则切换语言后会复用上一个语言的缓存。相关
更新日志
No recent changes