programing

i18n의 현재 로케일의 변경을 감시할 수 있는 방법이 있습니까?

bestcode 2022. 9. 25. 00:29
반응형

i18n의 현재 로케일의 변경을 감시할 수 있는 방법이 있습니까?

i18n 사용 중 언어/로케일이 변경되었을 때 함수를 호출하려면 어떻게 해야 하나요?
Vuex를 사용해야 합니까, 아니면 vue-i18n을 사용할 수 있는 방법이 있습니까?

볼 수 있다$i18n.locale보통 이런 거 많이 바꾸잖아요이러한 요구에 대한 사용 사례는 무엇입니까?

watch: {
  '$i18n.locale': function(newVal, oldVal) {
    console.log('locale change', newVal)
  }
}

/ src 디렉토리에 있는 I18n.js 파일:


import Vue from "vue";
import VueI18n from "vue-i18n";

Vue.use(VueI18n);

// 언어를 변경할 때 파일 /locals/language를 전환합니다.json

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;
}

// 미리 설정된 브라우저 언어를 확인하여 시작 시 설정

function detectLanguage() {
  const lng = window.navigator.userLanguage || window.navigator.language;
  const locales = require.context(
    "./locales",
    true,
    /[A-Za-z0-9-_,\s]+\.json$/i
  );
  const lang = locales
    .keys()
    .find((key) => lng.includes(key.replace("./", "").replace(".json", "")));
  return lang ? lang.replace("./", "").replace(".json", "") : null;
}

export default new VueI18n({
  locale:
    localStorage.getItem("lang") ||
    detectLanguage() ||
    process.env.VUE_APP_I18N_LOCALE,
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || "ko",
  messages: loadLocaleMessages(),
});

언급URL : https://stackoverflow.com/questions/67141277/is-there-a-way-to-watch-a-change-of-the-i18ns-current-locale

반응형