商城网站建设php网站维护工作内容
i18next是一个国际化相关的的依赖,适配多种框,比如vue2/3,react,next.js等等,是一个非常实用的依赖。在一次项目中接触过i18n相关内容,因此今天就整理一下这个通用的插件。
官网:Introduction | i18next documentation
i18next使用步骤:
1.安装依赖:npm install -S vue3-i18next
2.编辑配置文件
//我放在了public下,public/locales.js
import i18next from "i18next";
import { createI18n } from "vue3-i18next";const locales = {en: {message: {hello: 'Hello!',loadbundle: 'Load bundle language: {{lang}}',},},zh: {message: {//命名空间,相当于一个模块hello: '你好!',loadbundle: '当前语言: {{lang}}',},message2:{hello: '不好!',loadbundle: '当前语言: {{lang}}',}},
};
const options = {initImmediate: true,//是否异初始化lng: "zh",//默认语言fallbackLng: "zh",//回退语言,当前语言找不到对应翻译使用的语言saveMissing: true,//当翻译键缺失时,是否将缺失的翻译发送到服务器(适用于服务端管理语言包)。resources: {//设置更多语言en: {translation: locales.en,},zh: {translation: locales.zh,},},
};
i18next.init(options);
export const i18n = createI18n(i18next);
3.在main.js/main.ts中引入
import { createApp } from "vue";
import App from "./App.vue";
import {i18n} from "/public/locales"//引入第二步中暴露的内容const app = createApp(App);
app.use(i18n);//使用配置的内容
app.mount("#app");
4.在组件中使用
<template><div id="app"><p>{{ $t('message2.hello') }}</p>//两个设置的可切换语言的内容,命名空间+key<p>{{ loadbundle() }}</p>//因为loadbundle中有变量,所以使用方法传入变量<label for="language-select">选择语言:</label>//模拟切换语言<select id="language-select" v-model="lang" @change="changeLanguage(map[lang])"><option value="中文">中文</option><option value="English">English</option></select></div>
</template><script lang="ts" setup>
import { useI18next } from "vue3-i18next";
import { ref, watch } from "vue";
const i18n = useI18next();
let lang=ref('中文');
const map={//提供页面展示和语言配置之间的映射关系'中文':"zh",'English':"en"
}
const loadbundle = () => i18n.t('message.loadbundle', {lang: `${lang.value}`});//i18n.t 是 i18next 提供的翻译方法 t,用来获取翻译字符串。const changeLanguage = (val) => {i18n.changeLanguage(val); // 当select改变后切换语言
};</script>
上述就是一个完整的使用过程,本文以vue3作为案例,在其他框架中使用方法也类似。