i18n支持传入变量标识可以做变更文字显示,但如果要让这个变量显示组件的话需要用到插槽
在vue3中需要用i18n-t标签,keypath为i18n值的路径,<template #name>里面就可以放我们想要的组件
代码如下
i18n已全局引入,无需再引入i18n-t。
// routes.operConfig.json
{"low": "换电前电量低于{number1}%,换电后电量高于{number2}%,为有效换电"}
<i18n-t keypath="routes.operConfig.low">
<template #number1>
<InputNumber :max="100" v-model:value="formData.sysOperPowerReplace.beforeRate" />
</template>
<template #number2>
<InputNumber :max="100" v-model:value="formData.sysOperPowerReplace.afterRate" />
</template>
</i18n-t>
如何配置全局i18n
// main.js
import { setupI18n } from '@/locales/setupI18n';
// 异步案例:语言文件可能从服务器端获取
await setupI18n(app);
@/locales/setupI18n
import type { App } from 'vue';
import type { I18nOptions } from 'vue-i18n';
import { createI18n } from 'vue-i18n';
import { setHtmlPageLang, setLoadLocalePool } from './helper';
import { localeSetting } from '@/settings/localeSetting';
import { useLocaleStoreWithOut } from '@/store/modules/locale';
const { fallback, availableLocales } = localeSetting;
export let i18n: ReturnType<typeof createI18n>;
async function createI18nOptions(): Promise<I18nOptions> {
const localeStore = useLocaleStoreWithOut();
const locale = localeStore.getLocale;
const defaultLocal = await import(`./lang/${locale}.ts`);
const message = defaultLocal.default?.message ?? {};
setHtmlPageLang(locale);
setLoadLocalePool((loadLocalePool) => {
loadLocalePool.push(locale);
});
return {
legacy: false,
locale,
fallbackLocale: fallback,
messages: {
[locale]: message,
},
availableLocales: availableLocales,
sync: true, //If you don’t want to inherit locale from global scope, you need to set sync of i18n component option to false.
silentTranslationWarn: true, // true - warning off
missingWarn: false,
silentFallbackWarn: true,
};
}
// setup i18n instance with glob
export async function setupI18n(app: App) {
const options = await createI18nOptions();
i18n = createI18n(options);
app.use(i18n);
}
./helper.ts
import type { LocaleType } from '#/config';
export const loadLocalePool: LocaleType[] = [];
export function setHtmlPageLang(locale: LocaleTy