本文已参与「新人创作礼」活动,一起开启掘金创作之路。-- Vue3 中实现国际化
在 Vue3 中,我们可以使用 vue-i18n 插件来实现国际化。首先,你需要安装 vue-i18n 插件:npm install vue-i18n
然后,你可以在你的 Vue 项目中使用 vue-i18n 插件:
import Vue from 'vue';
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
const i18n = new VueI18n({
locale: 'zh-CN', // 默认语言
messages: {
'zh-CN': {
message: {
hello: '你好!'
}
},
en: {
message: {
hello: 'Hello!'
}
}
}
});
new Vue({
i18n,
render: h => h(App)
}).$mount('#app');
在上面的代码中,我们使用 vue-i18n 插件创建了一个 i18n 实例,并且设置了两种语言的翻译:简体中文和英文。
接下来,你就可以在你的 Vue 组件中使用 $t 方法来翻译字符串了:
<template>
<div>
{{ $t('message.hello') }}
</div>
</template>
在上面的代码中,我们使用了 $t 方法来翻译字符串。如果当前语言是简体中文,则会输出 '你好!';如果当前语言是英文,则会输出 'Hello!'。
如果你希望切换语言,你可以使用 $i18n.locale 来设置当前语言:
this.$i18n.locale = 'en';
在上面的代码中,我们使用 $i18n.locale 来将当前语言设置为英文。
除了使用 vue-i18n 插件,你还可以使用其他方法来实现 Vue3 中的国际化。
例如,你可以使用 vuex 来管理语言状态:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
locale: 'zh-CN'
},
mutations: {
SET_LOCALE(state, locale) {
state.locale = locale;
}
}
});
new Vue({
store,
render: h => h(App)
}).$mount('#app');
在上面的代码中,我们使用 vuex 来管理语言状态。在组件中,你可以使用 mapState 辅助函数来访问语言状态:
import { mapState } from 'vuex';
export default {
computed: {
...mapState(['locale'])
}
};
然后,你就可以在模板中使用 locale 变量来显示当前语言了:
<template>
<div>{{ locale }}</div>
</template>
如果你希望切换语言,你可以使用 mapMutations 辅助函数来调用 mutations:
import { mapMutations } from 'vuex';
export default {
methods: {
...mapMutations(['SET_LOCALE'])
}
};
在组件中,你可以使用 $store.commit 方法来提交 mutation:
this.$store.commit('SET_LOCALE', 'en');