vue项目引入vue-i18n,实现中英文切换

1、安装

vue-i18n官网:https://kazupon.github.io/vue-i18n/zh/

html页面引入

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>

npm包管理

npm install vue-i18n

2、使用方法

a、建立一个lang文件夹,文件夹新增en.js文件和cn.js文件

cn.js

export default {
  placeholder: {
    phone: '手机号',
    input_code: '输入验证码',
    passwordSix: '请输入6到18位密码'
  },
  sidebar: {
    MyAccount: '账户信息',
    PersonalInformation: '个人信息',
    Message: '我的消息',
    MyWallet: '我的钱包',
    MyProject: '我的方案'
  },
  home: {
    SendCode: 'Send verification code success'
  }
}

en.js

export default {
  placeholder: {
    phone: 'Phone Number',
    input_code: 'Verification code',
    passwordSix: 'Please enter 6 to 18 Bit passwords'
  },
  sidebar: {
    MyAccount: 'My Account',
    PersonalInformation: 'Personal Information',
    Message: 'Message',
    MyWallet: 'My Wallet',
    MyProject: 'My Project'
  },
  home: {
    SendCode: 'send Code Success功'
  }
}

b、在main.js中

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import VueI18n from 'vue-i18n'
import zh from "./common/lang/cn.js"
import en from "./common/lang/en.js"
Vue.config.productionTip = false;

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'zh',    // 语言标识
  //this.$i18n.locale // 通过切换 locale 的值来实现语言切换
  messages: { // js 方式
    'zh': zh,   // 中文语言包
    'en': en    // 英文语言包
  }
})

new Vue({
  router,
  store,
  i18n,
  render: (h) => h(App),
}).$mount("#app");

c、页面中使用

<template>
  <div class="home">
    {{ $t('sidebar.MyWallet') }}
    <button @click="changeLanguage()">click</button>
  </div>
</template>

<script>
export default {
  name: "Home",
  data() {
    return {
      lang: "zh",
    };
  },
  methods: {
    changeLanguage() {
      if (this.lang === "zh") {
        this.lang = "en";
        this.$i18n.locale = this.lang; //关键语句
      } else {
        this.lang = "zh";
        this.$i18n.locale = this.lang; //关键语句
      }
    },
  },
};

vue项目引入vue-i18n,实现中英文切换_第1张图片

你可能感兴趣的:(vue,js,前端)