0
点赞
收藏
分享

微信扫一扫

vue中使用i18n

蚁族的乐土 2022-01-04 阅读 55

下载i18n

  • yarn add -D vue0i18n

src目录下新建 i18n文件夹(en.js和zh.js)

  • en.js
import Vue from "vue";
import VueI18n from "vue-i18n";

Vue.use(VueI18n)  


var locale = "cn"
locale = localStorage.getItem("type") ? localStorage.getItem("type") : "zh"
console.log("locale",locale);
const i18n = new VueI18n({  
  locale: locale, // 语言标识  //语言状态 1:中文 2:英文 3:日文 4:韩文
  messages: {
    en: require("./en.js"), // 中文语言包
    zh: require("./zh") // 英文语言包
  }
})


export default i18n
  • zh.js
//en.js
module.exports = {
  lang: {
    home: '首页',
    about: '关于'
  }
}

页面中使用

<template>
  <div id="app">
    <ul>
      <li
        :class="{ 'active': changeIndex == item.status }"
        v-for="item in list"
        :key="item.status"
        @click="changeHandelr(item)"
      >
        {{ item.name }}
      </li>
    </ul>
    {{$t('lang.home')}}
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},
  data: () => ({
    list: [
      { status: 1, type: "zh", name: "中文" },
      { status: 2, type: "en", name: "英文" },
    ],
    changeIndex: localStorage.getItem("changeIndex") || 1,
  }),
  methods: {
    changeHandelr(item) {
      this.changeIndex = item.status;
      console.log(this.$i18n);
      this.$i18n.locale = item.type;
      localStorage.setItem("type",item.type)
      localStorage.setItem("changeIndex",item.status)
    },
  },
};
</script>

<style>
ul {
  display: flex;
}
li {
  list-style: none;
  width: 100px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 4px;
  background-color: #00f;
  color: #fff;
  cursor: pointer;
  margin-right: 10px;
}
.active {
  background-color: #f60;
}
</style>

展示如下:

在这里插入图片描述

举报

相关推荐

0 条评论