Vue实现多语言切换

安装i18n
vue add i18n

? The locale of project localization. zh   // 首选语言 zh
? The fallback locale of project localization. en  // 替代语言 en,首选语言中没有的会显示替代语言
? The directory where store localization messages of project. It's stored under 
`src` directory. locales   // 语言文件目录
? Enable locale messages in Single file components ? Yes  // 是否允许在组件中使用 messages

src/i18n.js

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

Vue.use(VueI18n);

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 getLanguage() {
  if (localStorage && localStorage.locale) {
    return localStorage.locale;
  }
  // 使用系统语言,如果语言文件中没有则使用 en
  return (navigator.language || navigator.userLanguage).split("-")[0];
}

// locale
export default new VueI18n({
  locale: getLanguage(),
  fallbackLocale: "en",
  messages: loadLocaleMessages(),
});

src/main.js

import Vue from 'vue'
import App from './App.vue'
import i18n from './i18n'

Vue.config.productionTip = false

new Vue({
  i18n,
  render: h => h(App)
}).$mount('#app')
语言文件目录

src/locales/en.json

{
  "message": "Hello i18n !!"
}

src/locales/zh.json

{
  "message": "你好 i18n !!"
}
多语言切换
<template>
  <div class="wrapper">
    <div class="content">
      <p>{{ $t("hello") }}</p>
      <div class="btns">
        <button
          :class="{ active: active === index }"
          v-for="(lang, index) of langs"
          :key="index"
          @click="changeLanguage(lang.value)"
        >
          {{ lang.label }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "HelloI18n",
  // "English", "中文", "Das ist Deutsch", "En français"
  data() {
    return {
      langs: [
        {
          label: "English",
          value: "en",
        },
        {
          label: "中文",
          value: "zh",
        },
        {
          label: "Das ist Deutsch",
          value: "de",
        },
        {
          label: "En français",
          value: "fr",
        },
      ],
    };
  },
  computed: {
    active() {
      const index = this.langs.findIndex(
        (item) => item.value === this.$i18n.locale
      );
      console.log(index);
      return index;
    },
  },

  methods: {
    changeLanguage(lang) {
      // 保存语言配置到localStorage
      localStorage.setItem("locale", lang);
      // 修改显示语言
      this.$i18n.locale = lang;
      // TODO 修改远程配置
    },
  },
  created() {},
};
</script>

<i18n>
{
  "en": {
    "hello": "Hello i18n !!"
  },
  "zh":{
    "hello":"你好, i18n !"
  },
  "fr":{
    "hello":"Bonjour i18n!"
  }
}
</i18n>
实现效果
d1xdbD.gif
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容