使用 Nuxt.js 和 Vue-i18n 重定向到同一页面但切换语言 url

Redirecting to the same page but switched language url, using Nuxt.js and Vue-i18n

当用户单击特定按钮以更改应用程序的语言时,我试图通过一种方法重定向用户。
这些按钮是标准布局的一部分,项目的所有页面都是其中的一部分,因此 url 可以根据用户所在的 .vue 页面而有所不同,但按钮是始终相同,这意味着重定向必须是动态的。

例如 url :

localhost/about


应通过方法(按特定按钮)重定向到:

localhost/bg/about


在项目中,页面位于文件夹 _locale 内,并且还从该文件夹外的 .vue 文件导入,如 Nuxt 文档中关于使用 Vue-i18n 进行本地化的建议 https://nuxtjs.org/examples/i18n/
nuxt.config.jsi18n.js 中间件、i18n.js 插件和 index.js 存储文件的实现方式相同。


因为它是一个 Nuxt.js 应用程序而不仅仅是一个 Vue.js 应用程序,只需通过更改 locale ( language) 实际上也不会改变语言,即使它改变了语言(例如使用 this.$i18n.locale = 'bg' )它也只会为特定页面改变它并且在下一个导航中它再次使用 fallback locale 相反,所以我试图通过重定向来解决它,重定向确实使用了基于 url 的语言的正确 .json 文件。我只是想找到一种方法让这种重定向更加动态,而不是只导航回每种语言的 home 页面。


如果需要 github 回购:https://github.com/alexgil1994/logistics-gls


需要的步骤:

npm install
npm run dev


可以用更好的方式完成吗?对于这种情况,有没有正则表达式的例子?有没有比 Regex 更简单的方法?
欢迎所有建议。

我提出这个问题已经有很长时间了,我忘记了我已经找到了一个自定义的解决方法,所以既然是时候为另一个项目再次实施它,我想最终关闭这个问题。

由于我再次搜索可能的国际化解决方案,我发现有两种可能(至少):

1).使用Nuxtvue-i18n的自定义解决方案是在he/she选择其中之一时使用用户触发的方法语言选择:

changeLanguage(locale) {
          // -- Getting the path before starting
          var beforePath = this.$nuxt.$router.history.current.path

          // -- Removing the previous locale from the url
          var result = ''
          result = beforePath.replace( "/bg", "" )
          result = result.replace( "/gr", "" )

          // -- Redirecting to the same page but in the desired language
          if ( locale == 'gr' || locale == 'bg' ) {
            this.$nuxt.$router.replace({ path: '/' + locale + result })
          } else {
            if ( result == '/' ) {
              this.$nuxt.$router.replace({ path: '/' + locale })
            } else {
              this.$nuxt.$router.replace({ path: '/' + locale + result })
            }
          }
      }

你可以看到我传入了 locale 参数,这是选择的语言代码,我们使用 $nuxt.$router 来获取当前路径。

2). 第二种解决方案是使用 nuxtnuxt-i18n 代替。这样就可以使用 switchLocalePath 中描述的方法 official documentation。虽然我还没有真正尝试过(我记得我在 8 个月前尝试过但遇到了一些问题,我可能以错误的方式实现了它)。很快就会再试一次。



希望这会对其他人有所帮助