当前位置:Gxlcms > JavaScript > 使用vue 国际化i18n 实现多实现语言切换功能

使用vue 国际化i18n 实现多实现语言切换功能

时间:2021-07-01 10:21:17 帮助过:162人阅读

安装

npm install vue-i18n

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

准备翻译信息

en.js

  1. export default {
  2. home: {
  3. helloworld: "hello workd !"
  4. }
  5. };

zh.js

  1. export default {
  2. home: {
  3. helloworld: "你好世界"
  4. }
  5. };

index.js

创建Vue-i18n实例

  1. import Vue from "vue";
  2. import VueI18n from "vue-i18n";
  3. import enLocale from "./en";
  4. import zhLocale from "./zh";
  5. Vue.use(VueI18n);
  6. const i18n = new VueI18n({
  7. locale: localStorage.lang || "zh",
  8. messages: {
  9. en: {
  10. ...enLocale
  11. },
  12. zh: {
  13. ...zhLocale
  14. }
  15. }
  16. });
  17. export default i18n;

i18n 挂载到 vue 根实例

main.js

  1. import Vue from "vue";
  2. import App from "./App.vue";
  3. import router from "./router";
  4. import store from "./store";
  5. import i18n from "./assets/i18n/index";
  6. Vue.config.productionTip = false;
  7. Vue.prototype.$i18n = i18n;
  8. new Vue({
  9. router,
  10. store,
  11. i18n,
  12. render: h => h(App)
  13. }).$mount("#app");

简单的使用

about.vue

  1. <template>
  2. <div class="about">
  3. <h1>{{ $t("home.helloworld") }}</h1>
  4. <button @click="changeLang()">切换英文</button>
  5. <p>{{hi}}</p>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. data: function() {
  11. return {};
  12. },
  13. computed: {
  14. hi() {
  15. return this.$t("home.helloworld");
  16. }
  17. },
  18. methods: {
  19. changeLang() {
  20. this.$i18n.locale = "en";
  21. }
  22. }
  23. };
  24. </script>

注意:

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

总结

以上所述是小编给大家介绍的使用vue 国际化i18n 多实现语言切换功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

人气教程排行