Struggling to make vue-i18n function properly with nuxt generate?

In an effort to enhance my skills, I am creating a small Nuxt project from scratch. While the project runs smoothly on the local server, I have encountered an issue with the language switcher not updating the translation fields when using nuxt generate.

Upon investigating the static site, it appears that vue-i18n is correctly filling the text fields with the default translation, all the translation locales are included in the deployed code, and the language switcher successfully modifies the window.$nuxt.$i18n.locale property. However, I suspect that I may be misunderstanding or misusing something in this process, as my attempts to find a solution through Google have been unsuccessful so far.

(I opted for vue-i18n instead of nuxt-i18n due to requirements in a previous job interview test, and I am repurposing my code for use in my portfolio.)

View source code here.

Check out the deployed site here.

Answer №1

To install vue-i18n, use the following command:

npm install vue-i18n

Add the plugin to nuxt.config.js file:

plugins: ['~/plugins/i18n.js']

Create a new file named plugins/i18n.js and add the following code:

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

export default ({ app, store }) => {

  app.i18n = new VueI18n({
    locale: store.state.locale,
    fallbackLocale: 'en',
    messages: {
      'en': require('~/locales/en.json'),
      'fr': require('~/locales/fr.json')
   }
  })

  app.i18n.path = (link) => {
    if (app.i18n.locale === app.i18n.fallbackLocale) {
      return `/${link}`
    }

    return `/${app.i18n.locale}/${link}`
  }
}

In your store index.js file, include the following code:

export const state = () => ({
  locales: ['en', 'fr'],
  locale: 'en'
})

export const mutations = {
  SET_LANG (state, locale) {
    if (state.locales.includes(locale)) {
      state.locale = locale
    }
  }
}

Create locals/en.json file with the following content:

{
  "links": {
    "home": "Home",
    "about": "About",
    "english": "English version",
    "french": "French version"
 },
  "home": {
    "title": "Welcome",
    "introduction": "This is an introduction in English."
  },
  "about": {
    "title": "About",
    "introduction": "This page is made to give you more information."
  }
}

Create locals/fr.json file with the following content:

{
  "links": {
    "home": "Accueil",
    "about": "À propos",
    "english": "Version Anglaise",
    "french": "Version Française"
  },
  "home": {
    "title": "Bienvenue",
    "introduction": "Ceci est un texte d'introduction en Français."
  },
  "about": {
    "title": "À propos",
    "introduction": "Cette page est faite pour vous donner plus d'informations."
  }
} 

Now, you can use i18n in your index.vue file:

<template>
  <div class="Content">
    <div class="container">
      <h1 class="Content__Title">
        {{ $t('home.title') }}
      </h1>
      <p>{{ $t('home.introduction') }}</p>
    </div>
  </div>
</template>
<script>
export default {

}
</script>

Answer №2

Update

The issue I encountered with the generate command stemmed from my use of v-if on the <nuxt> component.


Hossein's response appears to be a replica of https://nuxtjs.org/examples/i18n/, which I suggest revisiting for further clarity.

In my opinion, the middleware is essential. It is advisable not to rely on window.location but rather utilize nuxt-links such as

<nuxt-link :to="$i18n.path('about')">Home</nuxt-link>
or employ method form like this in your dropdown:

handleSelect(path) {
      this.$router.push({
        path: this.$i18n.path(path)
      });
    }

This approach has proven effective for me.

I have meticulously followed the Nuxt official example and all functionalities seem operational except for capturing the page title and meta description using nuxt generate.

If anyone has any valuable insights on this matter, they would be greatly appreciated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to send Multipart form data with a string payload

Many suggestions in regards to this issue recommend utilizing some form of FormData within nodejs for building a multipart form. However, I am seeking to achieve the same result without relying on the FormData library. Instead, I aim to use only request h ...

What is the best way to manage a 301 redirect from a current page to a new page within my index.js script?

Hello everyone, hope you're having a great Friday! I'm looking for advice on the best approach to handle a 301 redirect in node.js from an existing file to another file. Let's say I currently have a file called /contact router.get('/con ...

Capture any clicks that fall outside of the specified set

I am facing an issue with my navigation drop down menu. Currently, the pure CSS functionality requires users to click the link again to close the sub-menu. What I want is for the sub-menu to close whenever a click occurs outside of it. I attempted a solu ...

Organize the dataset into groups based on every possible key

Hi there, I'm facing a challenge while developing an application using NestJS/Prisma. The task at hand is to extract unique results from a table in order to display them in a filter on the front-end. Let me give you an overview of my table structure ...

Using the 'onended' audio event emitter in Angular 2 along with a local member of the Component

I'm looking for assistance on how to utilize audio.onended() in order to play the next song in a playlist. I can successfully add songs to the playlist and play them using the above method with an audioObject. However, when audio.onended triggers, I ...

Steps to import shared CSS using Styled-components

In my project using react, I've implemented styled-components for styling. One requirement is to have a shared loading background. Here is the code snippet of how I defined it: const loadingAnimation = keyframes` 0% { background-position: 95% 95%; } ...

Utilizing JavaScript to call functions from an ASP.NET code file

I am in need of assistance with integrating a JavaScript-based timeline that requires data from an SQL server. I have already developed the queries and JSON conversions using C#.NET functions within a code file associated with an .aspx page. As a newcomer ...

PhantomJs is only providing partial responses

I have been attempting to retrieve a response from the following URL using PhantomJS:- https://www.trivago.com/api/v1/bin/accommodation/2891353/deals?iPathId=34812&iRoomType=1&aRooms=&aDateRange%5Barr%5D=2017-05-24&aDateRange%5Bdep%5D=2017 ...

Unable to retrieve data from a nested object within a JSON structure

In my React project, I have created a function component like the one below: function FetchData() { const [randomUserData, setRandomUserData] = useState(''); const url = 'https://randomuser.me/api/'; const fetchData = () => { ...

Starting a Vue.js app with preloaded data

I have a single file component named Foo: <template> <div> This is the main app. X is {{ x }}, y is {{ y }} </div> </template> <script> export default { data() { return { x: 'hello x' }; }, } </script> ...

AngularJS Module Instantiation Error

My angularjs module is not loading correctly and I'm struggling to figure out why. Despite reading numerous tutorials, I can't seem to get it to work. [17:22:36.338] Error: [$injector:modulerr] Failed to instantiate module wc2013mongoMod due t ...

Locate and filter elements by using the react-testing-library's getAll method

On my page, I have a collection of unique checkbox elements that are custom-designed. Each individual checkbox has the following structure: <div className="checkbox" role="checkbox" onClick={onClick} onKeyPress={onKeyPress} aria-checked={getS ...

What is the method for creating a loop that includes a radio-like button?

https://i.stack.imgur.com/YkheU.jpg How can I create a button that functions like a radio button? What is this type of button called? And how can I add radio buttons in a loop similar to the image above? I know the button input needs to be wrapped with ...

Performing an AJAX request to the database when a change occurs, prior to submitting the

In my user setup/create form, I am including a field for the users' license/certification number which needs to be validated and returned to a specific DIV Onchange before the form is submitted. I have heard that using AJAX POST is the way to achieve ...

Angular: facing difficulty displaying static html pages on server, although they render correctly when run locally

Within my Angular project, I have stored a few static html files (specifically sampleText.html) in the src/assets/html folder. In one of my components, I am attempting to fetch and display this file. The following code is being used for this purpose. Every ...

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

Repairing the orientation in unique threejs capsule geometric shape

Exploring the realm of custom geometry in three.js, I decided to experiment with modifying Paul Bourke's capsule geometry example. However, as I delve into creating my own custom capsule geometry, I have encountered two main challenges: The orienta ...

Get the redirectUri using npm's Request package

When using npm Request to generate a response, I am able to retrieve information like "statusCode" by using "response.statusCode". However, I am unable to retrieve other information such as "redirectUri" as it shows undefined. Is there a way to access the ...

Remove an element from an array within objects

Need help with removing specific items from an array within objects? If you want to delete all hobbies related to dancing, you may consider using the splice method const people = [{ id: 1, documents: [{ ...

Navigating within a Vue application on the same pageWould you like assistance

I'm having an issue with my '/users' page. export default { name: 'Users', created () { const queryParams = this.$route.query this[GET_USERS_FROM_SERVER](queryParams) }, methods: { ...mapActions([GET_USERS_FROM ...