Vue i18n的使用

语言包

// /i18n/ch.js
export default {
  msg: '中文内容',
  name: '张三',
}
// /i18n/en.js
export default {
  msg: 'English Content',
  name: 'San Zhang',
}

注册i18n

// /i18n/index.js
import zh from "./ch";
import en from "./en";

export { zh, en };
// /i18n/install.js

import Vue from "vue";
import VueI18n from "vue-i18n";

//引入语言包
import { zh, en } from "./index";

Vue.use(VueI18n);

export const i18n = new VueI18n({
  locale: "en",
  messages: {
    ch: zh,
    en: en,
  },
});
import Vue from "vue";

import App from "./App.vue";
import { i18n } from "./i18n/install";

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

使用i18n

  1. 全局注册了$t,可以获取到自设的语言包
  2. 可以修改this.$i18n.locale来修改语言
<template>
  <div class="hello">
    <h1>{{ $t('msg') }}</h1>
    <button @click="change_lang">切换语言</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {}
  },
  methods: {
    change_lang() {
      //切换语言
      if (this.$i18n.locale === 'ch') {
        this.$i18n.locale = 'en'
      } else {
        this.$i18n.locale = 'ch'
      }
    },
  },
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值