安装
官网:https://vue-i18n.intlify.dev/api/general.html
pnpm add vue-i18n@9
使用
// @/locale/index.ts
import appConfig from "@/configure/app.config.ts";
import {nextTick} from 'vue'
import type {Ref} from 'vue'
import {createI18n} from 'vue-i18n'
import type {I18n, Locale} from 'vue-i18n'
const DEFAULT_LANG: string = appConfig.defaultLanguage;
const i18n = createI18n({
legacy: false, // 禁用传统模式,使用 composition api mode
locale: DEFAULT_LANG,
messages: {},
fallbackLocale: DEFAULT_LANG,
globalInjection: true,
});
const loadLocaleMessages = async (i18n: I18n, locale: Locale) => {
const messages = await import(`./lang/${locale}/index.ts`)
i18n.global.setLocaleMessage(locale, messages.default)
if (i18n.mode === "legacy") {
i18n.global.locale = locale;
} else {
(i18n.global.locale as Ref<Locale>).value = locale;
}
document.querySelector('html').setAttribute('lang', locale)
return nextTick();
}
loadLocaleMessages(i18n, DEFAULT_LANG)
export default i18n;
// @/locale/zh-CN/index.ts
const menu = {
"account": "用户菜单",
}
export default {
...menu
}
// @/main.ts
import i18n from "@/locale"
// const app = createApp(App)...
app.use(i18n)
// @/view/demo/demo.vue
<template>
<h1>{{ t('account') }}</h1>
<template>
<script setup lang="ts">
import {useI18n} from "vue-i18n";
const {t} = useI18n()
</script>
标签:vue,const,locale,vue3,ts,使用,i18n,import
From: https://www.cnblogs.com/fires/p/17741801.html