vue + vue-i18n 实现双语切换(中/英)

1. 在vue中安装vue-i18n,在package.json中查看是否已安装上     npm install vue-i18n --save-dev

2. 在src下建一个lang目录,分别存放 中英文文件 按不同模块存放在module下

我这里使用了element组件 element内部的语言也需要切换

 

3. 在main中引入

4. 文本  $t("test.home")

this.$i18n.locale来更改中英文

可以在localStorage中写入当前的语言 这样刷新的时候不会又切回切换前的语言

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">{{ $t("test.home") }}</router-link> |
      <router-link to="/about">{{ $t("test.about") }}</router-link>
      {{ $t("test.test") }}
      <el-button @click="switchLanguage">{{ $t("test.switch") }}</el-button>
    </div>
    <router-view />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {};
  },
  methods: {
    switchLanguage() {
      this.$confirm(this.$t("test.toggle"), this.$t("test.tips"), {
        confirmButtonText: this.$t("test.ok"),
        cancelButtonText: this.$t("test.cancel"),
        type: "warning"
      })
        .then(() => {
          let locale = this.$i18n.locale;
          locale === "zh"
            ? (this.$i18n.locale = "en")
            : (this.$i18n.locale = "zh");
          window.localStorage.locale = this.$i18n.locale; // 在localStorage中存入当前locale
          // console.log(
          //   this.$i18n.locale + "local:" + window.localStorage.locale
          // );
          this.$message({
            type: "success",
            message: "切换成功"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "未切换"
          });
        });
    }
  }
};
</script>

参考借鉴了这位大佬写的  大佬的链接


版权声明:本文为qq_40984565原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。