自定义路由路径
nuxt/i18n v7 自定义路由路径。
在某些情况下,您可能想要翻译 URL,除了用语言代码进行前缀标记之外。可以通过两种方式配置页面的自定义路径:组件内部选项 或者通过 模块的配置。
使用
no_prefix
策略 时不支持自定义路径。组件内部选项
将 nuxtI18n.paths
属性添加到您的页面,并在其中设置自定义路径:
pages/about.vue
export default {
nuxtI18n: {
paths: {
en: '/about-us', // -> 访问路径为 /about-us (没有前缀,因为它是默认语言)
fr: '/a-propos', // -> 访问路径为 /fr/a-propos
es: '/sobre' // -> 访问路径为 /es/sobre
}
}
}
要为动态路由配置自定义路径,您需要像在 vue-router 中那样将参数放入 URI 中。
pages/articles/_name.vue
export default {
nuxtI18n: {
paths: {
en: '/articles/:name',
es: '/artículo/:name'
}
}
}
模块的配置
确保将 parsePages
选项设置为 false
,以禁用 babel 解析,并在 pages
选项中添加自定义路径:
nuxt.config.js
i18n: {
parsePages: false, // 禁用 babel 解析
pages: {
about: {
en: '/about-us', // -> 访问路径为 /about-us (没有前缀,因为它是默认语言)
fr: '/a-propos', // -> 访问路径为 /fr/a-propos
es: '/sobre' // -> 访问路径为 /es/sobre
}
}
}
请注意,pages
对象中的每个键应对应于您 pages/
目录中路由的相对文件路径,不包括前导的 /
。
自定义路由路径必须以 /
开头,并且不包括语言前缀。
示例 1
假设您有一些嵌套页面,如:
pages/
├── _nested/
├──── _route/
├────── index.vue
├────── _.vue
以下是如何在配置中配置这些特定页面的方法:
nuxt.config.js
i18n: {
parsePages: false,
pages: {
'_nested/_route/index': {
en: '/mycustompath/:nested/:route?' // 参数需要像在 vue-router 中那样被放回这里
},
'_nested/_route/_': {
en: '/mycustompath/:nested/*' // * 将匹配 /:nested/ 之后的整个路由路径
}
}
}
示例 2
对于以下 pages
目录:
pages/
├── about.vue
├── services/
├──── index.vue
├──── development/
├────── index.vue
├────── app/
├──────── index.vue
├────── website/
├──────── index.vue
├──── coaching/
├────── index.vue
您需要将 pages
属性设置如下:
nuxt.config.js
i18n: {
parsePages: false,
pages: {
about: {
en: '/about',
fr: '/a-propos',
},
'services/index': {
en: '/services',
fr: '/offres',
},
'services/development/index': {
en: '/services/development',
fr: '/offres/developement',
},
'services/development/app/index': {
en: '/services/development/app',
fr: '/offres/developement/app',
},
'services/development/website/index': {
en: '/services/development/website',
fr: '/offres/developement/site-web',
},
'services/coaching/index': {
en: '/services/coaching',
fr: '/offres/formation',
}
}
}
如果某个语言缺少自定义路径,则使用 defaultLocale
自定义路径(如果已设置)。