使用vue-i18n实现中英文切换

源码地址 :vue-i18n-demo

  1. 安装 vue-i18n

    npm install vue-i18n --save-dev
    
  2. 新建中英文对照文件

    // zh.js
    module.exports = {
      language: {
        name: "中文",
        current: "当前语言"
      },
      navbar: {
        home: "首页",
        about: "关于我们",
        join: "加入我们",
        contact: "联系我们"
      }
    };
    
    // en.js
    module.exports = {
      language: {
        name: "English",
        current: "Current Language"
      },
      navbar: {
        home: "Home",
        about: "About",
        join: "Join Us",
        contact: "Contact Us"
      }
    };
    
  3. 在 main.js 文件引入

    // main.js
    import VueI18n from "vue-i18n";
    
    Vue.use(VueI18n);
    const i18n = new VueI18n({
      locale: localStorage.getItem("lang") || "zh",
      messages: {
        zh: require("./assets/i18n/zh"),
        en: require("./assets/i18n/en")
      }
    });
    
    new Vue({
      router,
      i18n,
      render: h => h(App)
    }).$mount("#app");
    
  4. 使用

    <template>
      <div>
        <ul class="lang" @click="changeLang">
          <li :class="isActive?'active':''">zhli>/
          <li :class="!isActive?'active':''">enli>
        ul>
        <div>{{$t('language.current')}}:{{$t('language.name')}}div>
        <ul>
          <li>{{ $t('navbar.home') }}li>
          <li>{{ $t('navbar.about') }}li>
          <li>{{ $t('navbar.join') }}li>
          <li>{{ $t('navbar.contact') }}li>
        ul>
      div>
    template>
    
    <script>
    export default {
      name: "I18nDemo",
      data() {
        return {
          isActive: true
        };
      },
      created() {
        let lang = document.documentElement.lang;
        localStorage.setItem("lang", lang);
        this.toActive(lang);
      },
      methods: {
        changeLang(e) {
          let lang = e.target.innerText;
          this.$i18n.locale = lang;
          this.toActive(lang);
        },
        toActive(lang) {
          this.isActive = lang == "zh" ? true : false;
        }
      }
    };
    script>
    

    注: $t 是固定用法

  5. 效果:

    使用vue-i18n实现中英文切换_第1张图片

你可能感兴趣的:(Vue)