当前位置: 移动技术网 > IT编程>网页制作>CSS > vue 国际化i18n 多语言切换

vue 国际化i18n 多语言切换

2018年10月11日  | 移动技术网IT编程  | 我要评论

安装

npm install vue-i18n

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

准备翻译信息

en.js

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

zh.js

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

index.js

创建vue-i18n实例

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.js

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");

简单的使用

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内

 

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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网