切换 i18n 语言环境 vuex

时间:2021-02-02 07:03:32

标签: vue.js vuex vue-i18n

我使用 vuex 和 i18n 通过切换按钮更改语言,该按钮保存在本地存储中,但我无法动态更改语言,除非我通过在本地 i18n.js 文件中指示刷新页面:localStorage.getItem ('Language' ), 这是我的代码

文件 i18n.js


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

const i18n = createI18n({
// locale: 'fr',
locale: localStorage.getItem('Language'),
fallbackLocale: 'fr',
messages: loadLocaleMessages()
});
export default i18n;

我的突变 在我保存在本地存储中的突变中,如果语言为真 en 否则 fr 我在 location.reload() 中添加了突变;它有效,但我不确定这是最佳方法


export default {
  toggleLangMode: state => {
    state.Language = !state.Language;
location.reload ()
    if (state.Language === true) {
      state.name = 'en';
    } else {
      state.name = 'fr';
    }
    // console.log(i18n);
    localStorage.setItem('Language', state.name);
  },
  initializeLangMode: (state, payload) => {
    state.Language = payload; // payload is actually the value that was stored in the local storage
  }
};

切换文件

这里我看看在 fr 或 en 的 localestorage 中切换按钮的变化是否发生了变化

  <div class="widgets" :class="isDarkMode ? 'night' : 'day'">
    <div class="date"><Date /></div>
    <div class="containerWeather"><Weather /></div>
    <div class="toggleLang">
      <ToggleBtn
        theme="toggleLanguage"
        labelOn="English"
        labelOff="Français"
        v-model:value="isLang"
        @input="language"
      />
    </div>
  </div>
</template>

<script>
import ToggleBtn from '../../atoms/ToggleBtn/index.vue';
import Date from '@/components/atoms/Date';
import Weather from '@/components/atoms/Weather';
import { mapMutations, mapGetters } from 'vuex';

export default {
  name: 'Widgets',
  components: {
    ToggleBtn,
    Weather,
    Date
  },

  data() {
    return {
      isLang: this.Language
    };
  },
  methods: {
    ...mapMutations('langMode', ['toggleLangMode', 'initializeLangMode']),

    language() {
      this.toggleLangMode();
    }
  },

  computed: {
    ...mapGetters('langMode', ['Language'])
  },
  watch: {
    Language(newLang) {
      this.isLang = newLang;
    }
  },
  mounted() {
    const Language = localStorage.getItem('Language');
    if (Language && Language === 'fr') {
      this.initializeLangMode(false);
      this.isLang = false;
    } else {
      this.initializeLangMode(true);
      this.isLang = true;
    }
  }
};
</script>

0 个答案:

没有答案