vue+i18n实现语言切换

 第一步:安装i18n(以npm为例)

npm install vue-i18n

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

第二步:创建一些文件夹备用

 

 

 第三步:在main.js中注册组件

 

 

第四步:i18n/index.js

 

 

import Vue from "vue";
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)

import messages from "./lang"
// 通过选项创建 VueI18n 实例
export default new VueI18n({
    locale: 'zh', // 设置地区,初始语种
    messages, // 设置地区信息
})

第五步:lang/index.js

 

 

import zh from "./zh"
import en from "./en"
import ja from "./ja"

const messages = {
    //你需要进行切换的语种
    zh,
    en,
    ja
}
export default messages

第六步:zh.js(中文)

export default {
    msg: {
        hello: '你好,世界',
        mainoptions: "主选项",
        algorithm: "算法",
        weather: "天气",
        internationalization: "国际化"
    }
}

第七步:en.js(英文)

export default {
    msg: {
        hello: 'hello world',
        mainoptions:"mainoptions",
        algorithm:"algorithm",
        weather:"weather",
        internationalization:"internationalization"
    }
}

第八步:ja.js(日文)

export default {
    msg: {
        hello: 'こんにちは、世界',
        mainoptions: "主な選択肢",
        algorithm: "アルゴリズム",
        weather: "天気",
        internationalization: "国際化"
    }
}

第九步:调用

  this.$i18n.locale = “语种(zh,ja,en等)”;

ps:6、7、8步是你需要的语种,可以根据所需添加其他语种,只要保证对应的冒号前面的一致就行

ps1:调用的时候使用  this.$i18n.locale

ps2:在使用过程中,记得将你要进行语种切换的文本代码用 {{ $t("") }}来实现 ,例如:{{ $t("msg.hello") }} 这句话打印出来是“你好,世界”

 

效果

日文:

 

 英文:

 

 

中文:

 

 html代码:

<template>
  <div class="LanguageBox">
    <div class="Language">
      <p>{{ $t("msg.hello") }}</p> //ps2中提到的问题
    </div>
    <div class="LanguageChange">
      <div class="LanguageButton" @click="toggle('en')">切换(英文)</div>
      <div class="LanguageButton" @click="toggle('zh')">切换(中文)</div>
      <div class="LanguageButton" @click="toggle('ja')">切换(日文)</div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {};
  },
  mounted() {},
  methods: {
    toggle(zz) {
      this.$i18n.locale = zz;
    },
  },
};
</script>
<style lang="less" scoped>
.LanguageBox {
  width: 100%;
  height: 100%;
}
.Language {
}
.LanguageChange {
  display: flex;
  width: 100%;
}
.LanguageButton {
  margin: 1px 21px;
  width: 100px;
  height: 46px;
  background-color: #8b8b9b;
  color: #fff;
  line-height: 46px;
  border-radius: 10%;
  cursor: pointer;
}
</style>

 

posted @ 2021-05-14 10:52  草莓糖&薄荷茶  阅读(385)  评论(0)    收藏  举报