vue 国际化i18n 多语言切换

安装vue

npm install vue-i18n

新建一个文件夹 i18n ,内新建 en.js zh.js index.js 三个文件npm

准备翻译信息app

en.js学习

export default {
  home: {
    helloworld: "hello workd !"
  }
};

zh.jsthis

export default {
  home: {
    helloworld: "你好世界"
  }
};

index.jsspa

建立Vue-i18n实例prototype

import Vue from "vue";
import VueI18n from "vue-i18n";
import enLocale from "./en";
import zhLocale from "./zh";

Vue.use(VueI18n);
const i18n = new VueI18n({
  locale: localStorage.lang || "zh",
  messages: {
    en: {
      ...enLocale
    },
    zh: {
      ...zhLocale
    }
  }
});
export default i18n;

i18n 挂载到 vue 根实例翻译

main.jscode

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import i18n from "./assets/i18n/index";

Vue.config.productionTip = false;

Vue.prototype.$i18n = i18n;

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

简单的使用router

about.vue

<template>
  <div class="about">
    <h1>{{ $t("home.helloworld") }}</h1>
    <button @click="changeLang()">切换英文</button>
    <p>{{hi}}</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {};
  },
  computed: {
    hi() {
      return this.$t("home.helloworld");
    }
  },
  methods: {
    changeLang() {
      this.$i18n.locale = "en";
    }
  }
};
</script>

注意:

好比说上面的hi 你要经过这种形式来写的时候,不能放在data 里面,由于当语言切换的时候 他是不会变的 ,要写在computed内

 

此随笔乃本人学习工做记录,若有疑问欢迎在下面评论,转载请标明出处。

若是对您有帮助请动动鼠标右下方给我来个赞,您的支持是我最大的动力。

相关文章
相关标签/搜索