Skip to content

一、快速入门

一、准备工作

1、新建locales文件夹和lang子文件夹

bash
├─locales
  └─lang

2、新建zh-cn.tsen.ts

typescript
export default {
	user: {
		dynamic: '近期动态',
		info: '个人信息',
		settings: '设置',
		nightmode: '黑夜模式',
		nightmode_msg: '适合光线较弱的环境,当前黑暗模式为beta版本',
		language: '语言',
		language_msg: '翻译进行中,暂翻译了本视图的文本',
	}
}
typescript
export default {
	user: {
		dynamic: 'Dynamic',
		info: 'User Info',
		settings: 'Settings',
		nightmode: 'night mode',
		nightmode_msg: 'Suitable for low light environment,The current night mode is beta',
		language: 'language',
		language_msg: 'Translation in progress,Temporarily translated the text of this view',
	}
}

二、配置i18n

1、新建index.ts

typescript
import el_zh_cn from 'element-plus/es/locale/lang/zh-cn'
import el_en from 'element-plus/es/locale/lang/en'
import { createI18n, LocaleMessages ,I18nOptions} from 'vue-i18n';

import zh_cn from './lang/zh-cn';
import en from './lang/en';
import tool from '@/utils/tool';
import sysConfig from "@/config"

type MessageSchema = {
    el: typeof el_zh_cn | typeof el_en;
    [key: string]: any;
}

const messages:LocaleMessages<MessageSchema>={
    'zh-cn':{
        el: el_zh_cn,
        ...zh_cn
    },
    'en':{
        el: el_en,
        ...en
    }
}

const ii8n=createI18n({
    locale: tool.data.get("APP_LANG") ||  sysConfig.LANG,
    legacy:false,
    fallbackLocale:"zh-cn",
    globalInjection:true,
    messages
} as I18nOptions)

export default ii8n;

2、引入main.ts

typescript
import { createApp } from 'vue'
import App from './App.vue'
import ii8n from './locales'


const app=createApp(App)
app.use(ii8n)
app.mount('#app')

三、使用

1、模版内使用

语法

typescript
$t("user.info")

2、script使用

typescript
import{useI18n} from "vue-i18n"

const {locale}=useI18n();
// 切换语言
const configLang = (command: Language) => {
    // 修改语言
    language.value = command.value

    // 修改i18n配置
    locale.value=command.value

    // 本地存储语言
    tool.data.set("APP_LANG", command.value);
}