在某些情况下,您可能希望除了以区域代码为前缀外,还要翻译 URL。有两种方式可以为页面配置自定义路径:组件内选项 或通过 模块配置。
no_prefix
策略 时不支持自定义路径。在您的页面中添加 nuxtI18n.paths
属性,并在其中设置您的自定义路径:
export default {
nuxtI18n: {
paths: {
en: '/about-us', // -> 可以在 /about-us 访问(因为是默认地区,所以没有前缀)
fr: '/a-propos', // -> 可以在 /fr/a-propos 访问
es: '/sobre' // -> 可以在 /es/sobre 访问
}
}
}
要为动态路由配置自定义路径,您需要按照在 vue-router 中的方式将参数放入 URI 中。
export default {
nuxtI18n: {
paths: {
en: '/articles/:name',
es: '/artículo/:name'
}
}
}
确保将 parsePages
选项设置为 false
以禁用 babel 解析,并在 pages
选项中添加您的自定义路径:
i18n: {
parsePages: false, // 禁用 babel 解析
pages: {
about: {
en: '/about-us', // -> 可以在 /about-us 访问(因为是默认地区,所以没有前缀)
fr: '/a-propos', // -> 可以在 /fr/a-propos 访问
es: '/sobre' // -> 可以在 /es/sobre 访问
}
}
}
请注意,pages
对象中的每个键应对应于 pages/
目录中路由的相对文件路径,不包括前导的 /
。
自定义路由路径必须以 /
开头,并且不包括地区前缀。
假设您有一些嵌套页面如下所示:
pages/
├── _nested/
├──── _route/
├────── index.vue
├────── _.vue
以下是您在配置中配置这些特定页面的方式:
i18n: {
parsePages: false,
pages: {
'_nested/_route/index': {
en: '/mycustompath/:nested/:route?' // 参数需要在这里放回,就像您在 vue-router 中一样
},
'_nested/_route/_': {
en: '/mycustompath/:nested/*' // * 将匹配 /:nested/ 之后的整个路由路径
}
}
}
使用以下 pages
目录:
pages/
├── about.vue
├── services/
├──── index.vue
├──── development/
├────── index.vue
├────── app/
├──────── index.vue
├────── website/
├──────── index.vue
├──── coaching/
├────── index.vue
您需要将 pages
属性设置如下:
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
自定义路径(如果已设置)。