無法動態變更Vue i18n的區域設置
P粉211600174
P粉211600174 2024-03-21 17:40:26
0
1
428

我有一個小型 vue 應用程序,我想在其中實作 vue-i18n 插件以使我的應用程式多語言。我已經從 vue cli 安裝了 vue-i18n 插件。我有兩個區域設置,一切都按預期工作 - 每當我手動將區域設置從 .env 文件更改為所需語言時,應用程式中的語言也會更改。但是,每當我嘗試使用前端上的按鈕更改它時,我都會失敗這樣做。

這是我的 i18n.js 檔案中的內容:

import { createI18n } from 'vue-i18n'

function loadLocaleMessages() {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i);
  const messages = {};
  locales.keys().forEach(key => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  })
  return messages;
}

export default createI18n({
  legacy: false,
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages()
})

這是在 .env 檔案中:

VUE_APP_I18N_LOCALE=en
VUE_APP_I18N_FALLBACK_LOCALE=en

這是我看到的教程中的程式碼,他們透過 this.$i18n.locale 存取語言環境,但是,這對我不起作用,這就是我嘗試實現它的方式:

<template>
  <div class="hello">
    <h1>Hello World</h1>
    <h2>{{ t("hello") }}</h2>
    <h2>{{ t("message") }}</h2>
    <button @click="SetLocale('en')">EN</button>
    <button @click="SetLocale('nl')">NL</button>
  </div>
</template>
    
<script>
import { useI18n } from "vue-i18n";
export default {
  name: "HelloWorld",
  setup() {
    const { t } = useI18n({
      inheritLocale: true,
      useScope: "local",
    });

    // Something todo ..

    return {
      t
    };
  },
  methods: {
    SetLocale(locale) {
      console.log(locale);
      this.$i18n.locale = locale;
    },
  },
};
</script>
    
<i18n>
{
  "en": {
    "hello": "Hello i18n in English! (from component)",
  },
  "nl": {
    "hello": "Hello i18n in Dutch! (from component)",
  }
}
</i18n>

點擊按鈕時出現的錯誤是:

[Vue warn]:執行本機事件處理程序期間出現未處理的錯誤

未捕獲類型錯誤:無法設定未定義的屬性(設定 '語言環境')

我嘗試了一些其他解決方案,例如 i18n.locale 和 this.$root.$i18n.locale 但它們似乎也不起作用。

此外,當我嘗試訪問來自區域設定資料夾中的 JSON 檔案的訊息的

{{ t("message") }}

時,我收到這些警告:

[intlify] 在「nl」區域設定訊息中找不到「message」鍵。

[intlify] 回退到用「en」語言環境翻譯「message」鍵

[intlify] 在「en」區域設定訊息中找不到「Message」鍵。

[intlify] 回退到使用「nl」語言環境翻譯「message」鍵

我的問題是,我在哪裡做錯了什麼,有沒有辦法擺脫當我嘗試從區域設定資料夾存取 JSON 檔案時收到的警告?

P粉211600174
P粉211600174

全部回覆(1)
P粉132730839

我正在使用組合,所以不能 100% 確定這對你有用,但這對我有用:

更改自

i18n.locale = selectedLocale

i18n.global.locale = selectedLocale

希望有幫助。 :)

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!