[英]Get language from nuxt.js middleware
Is there a way in nuxt.js middleware to know the language used for the request (of the page)?在 nuxt.js 中间件中有没有办法知道用于请求(页面)的语言?
By taking the example proposed by nuxt.js ( https://nuxtjs.org/api/pages-middleware/ ) and by supposing that for example a page declined in two languages (French and English) with the following urls:以 nuxt.js ( https://nuxtjs.org/api/pages-middleware/ ) 提出的例子为例,假设一个页面以两种语言(法语和英语)被拒绝,网址如下:
When visiting the first or second url, can we have an indicator on the language used directly in the middleware?访问第一个或第二个 url 时,我们可以在中间件中直接使用语言的指示符吗? Or should you parse the page url to find out (route)?
还是应该解析页面 url 以找出(路由)?
Because I want to redirect the user according to the language requested...因为我想根据请求的语言重定向用户...
If you're using nuxt-i18n
module, is really simple, and you have two ways of doing it.如果您使用的是
nuxt-i18n
模块,那真的很简单,您有两种方法可以做到。 I'll suggest the first, but I think it would be cool to give a perspective on how the module works.我会建议第一个,但我认为对模块的工作方式给出一个观点会很酷。
Both of the solutions have the same starting point, getting the i18n
from the middleware context
.两种解决方案都有相同的起点,从中间件
context
获取i18n
。 i18n
should be accessed from the app
parameters from the context
, so we start from here: i18n
应该从context
的app
参数中访问,所以我们从这里开始:
export default async function({ app: { i18n } }) {}
i18n
module do the hard lifting i18n
模块做硬举The same way you can access the translations inside Vue components using the $t
method, we could use it from the i18n
object directly.与使用
$t
方法访问 Vue 组件内部翻译的方式相同,我们可以直接从i18n
对象中使用它。 So if you would write in a Vue Component所以如果你想写一个 Vue 组件
$t('components.login.register')
Then in the middleware you would do然后在中间件中你会做
i18n.t('components.login.register')
i18n
module better i18n
模块If you inspect the i18n
object that the module exposes, you can find the following parameters is contains:如果您检查模块公开的
i18n
对象,您会发现包含以下参数:
locale
- That represents the current language locale
- 代表当前语言messages
- An object that keeps the translations for each active language messages
- 保存每种活动语言翻译的对象so you could easily get the previous example translation like this:所以你可以很容易地得到前面的示例翻译,如下所示:
const { messages, locale } = i18n
const currentTranslations = messages[locale]
const wantedTranslation = currentTranslations.components.login.register
I'd suggest for you to use the i18n.t
module, as it works some of the abstractions you'd need to rewrite yourself, but it's a good example to understand the module better.我建议您使用
i18n.t
模块,因为它可以处理您需要自己重写的一些抽象,但这是更好地理解该模块的一个很好的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.