语言包
// /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
- 全局注册了$t,可以获取到自设的语言包
- 可以修改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>