0

I want to get access to this.$el in asyncData. I use a database to store translations. I want to get a list of translations that are used on the current page. Then I will send a request to the server to receive them. After that, I will merge it.

i18.mergeLocaleMessage( locale, message )

How to do it ?

4
  • What did you tried so far ? What do you mean by $el? Commented Apr 23, 2021 at 9:52
  • @kissu I want to get access to template, before it is mounted. it is necessary for seo. Commented Apr 23, 2021 at 9:56
  • Like a specific div ? Usually, you do have the SEO in the head(). Other info, can be get through $refs or the script tag. Do you have an example template of what you do want to get ? Commented Apr 23, 2021 at 10:02
  • No. I use nuxt-i18n for translate. In template {{ $t('Hello') ]}, when there is access to $ el, then translations are already loaded, and I want to load them for the current page. Commented Apr 23, 2021 at 10:05

1 Answer 1

2

You can access i18n with something like this, no need to access the template for this use case

asyncData ({ app }) {
  console.log(app.i18n.t('Hello'))
}

Looking at the lifecycle of Nuxt, asyncData will happen before any template is generated at all, so it is impossible with asyncData.
And even if it was possible with some hacky trick, it would be a bit strange to have to look inside of your template to then have some logic for i18n fetching.

Why not getting a computed nested object and loop on this through your template, after you have fetched all of your required translations ?

Also, you're using asyncData + an API call each time ? So, for every page: you will stop the user, let him wait for the API call and then proceed ?

Latest point, if you are on your page and you hit F5, then asyncData hook will not be triggered. Just to let you know about this caveat.

Alternative solutions:

  • using the fetch() hook and display a loader until you have fetched all your translations, still better to not rely on the content of the template. This will work even on F5 and can produce a more smooth experience (by not blocking the navigation).
  • getting your i18n whole translations globally, at some point when your user's connection is idle. Rather than on per-page. Especially because you will need to handle the logic of not fetching some translations that you already have (if the user visits a page twice).
Sign up to request clarification or add additional context in comments.

2 Comments

How do I know what translations are needed for a page?
Edited my answer. Also, do you use nuxt as universal or SPA only ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.