本地多语言切换具体操作代码
在src目录下创建utils文件夹,创建i18n.js文件以及存放语言的lang文件夹,方便管理。
1.设置i18n.js文件,处理本地语言,包含初始化和语言切换,需要通过项目需求替换不同的存储方式如uni.setStorageSync ,localhost,vuex等
const locales = {zh: require("./lang/zh.json"),en: require("./lang/en.json"),ft: require("./lang/ft.json"),fr: require("./lang/fr.json"),hy: require("./lang/hy.json"),jp: require("./lang/jp.json"),py: require("./lang/py.json"),
};let currentLocale = "";if (!uni.getStorageSync("locale")) {const systemLanguage = uni.getSystemInfoSync().language; // 首次进入使用系统默认语言,也可以根据自己项目需求改写此处的逻辑currentLocale = systemLanguage.startsWith("zh") ? "zh" : "en";
} else {currentLocale = uni.getStorageSync("locale"); // 用户切换过语言,使用用户上次切换的语言
}const i18n = {t(key) {return locales[currentLocale][key] || key;},setLocale(locale) {if (locales[locale]) {currentLocale = locale;// 切换语言后存储在本地,下次进入页面使用用户切换过的语言uni.setStorageSync("locale", currentLocale);} else {console.warn(`Locale ${locale} not found`);}},
};
export default i18n;
2.在main.js文件中引入创建的本地语言包,通过相对路径或是绝对路径去引入创建的i8n.js文件,通过vue的原型链方法,把本地的i18n添加到vue中。
import i18n from "./utils/i18n";
Vue.prototype.$i18n = i18n;
3.在lang中有很多语言,每个json文件保存一种语言。
{"language": "请选择语言"}
4.在页面中如何使用?在步骤 2 中,已经添加到了vue原型中。项目中可以通过$i18n.t + 具体的json字段即可
语言切换
具体如何把多语言本地化到项目中已经告诉你了,现在可以说说具体如何实现项目中的功能吧。
在项目中经常遇到支持多语言的需求,这往往需要大量的json字段,其中的语言切换功能实现如下:
// An highlighted blockconst activeLang = this.cabinetList.find((item) => item.active);let locale = activeLang ? activeLang : { name: "zh" };uni.setStorageSync("selectedLanguage", locale.name);console.log("切换", locale);this.$i18n.setLocale(locale.name);this.$forceUpdate(); // 强制更新视图setTimeout(() => {uni.navigateTo({url: "/pages/applicationSub/selectPrint?type=Detail",});}, 500);
事件触发后执行这段代码,就可以切换到相应的语言到整个项目了。这里是通过uni.setStorageSync方法设置的,你可能又有问题,什么时候获取这个selectedLanguage。
初始化获取语言
项目往往进入后会有一个默认语言,这是如何实现的?我是如何做的?
已H5项目为例,进入页面onLoad,onShow等方法,我在onLoad时通过uni.getStorageSync获取了这个代表状态切换的值,第一次进入是没有值的,需要添加判断逻辑来赋值一个默认值。
具体实现:
loadSavedLanguage() {const savedLang = uni.getStorageSync("selectedLanguage");if (savedLang) {// 更新语言列表的选中状态this.cabinetList.forEach((item) => {item.active = item.name === savedLang;});// 同步更新i18n语言this.$i18n.setLocale(savedLang);} else {const zhItem = this.cabinetList.find((item) => item.name === "zh");localStorage.setItem("selectedLanguage", "zh");uni.setStorageSync("selectedLanguage", "zh");if (zhItem) zhItem.active = true;}},
这里先获取一下缓存的值,如果没有就表示第一次进入,走了else判断,先遍历了语言列表,找到默认值“zh”,缓存后设置zhItem.active = true 选中语言。这个acticve是列表中的选中样式。
这个语言判断一般放在扫码结果的处理中,或是onLoad这种页面初始加载的生命周期中,符合页面初始化后语言默认加载的需求。
以下是完整代码:
// A code block<view class="list-container"><uni-scroll-view class="scroll-view"><u-list><u-list-item v-for="(item, index) in cabinetList" :key="index"><viewclass="list-item":class="item.active ? 'active' : ''"@click="handleClick(index, item)"><view class="item-content"><view class="item-title">{{ item.type }} </view><view class="item-status" v-if="item.active"><u-icon name="checkmark" color="#3b70ff"></u-icon></view></view></view></u-list-item></u-list></uni-scroll-view><view class="btns2 mb-40"><view class="btn back submit" @click="switchLanguage()">{{ $i18n.t("Confirm") }}</view></view></view>
cabinetList: [{type: "English",name: "en",onlay: "英语",active: false,number: 1,},{type: "简体中文",name: "zh",onlay: "中文简体",active: false,number: 2,},{type: "繁體中文",name: "ft",onlay: "中文繁体",active: false,number: 3,},{type: "Francais",name: "fr",onlay: "法语",active: false,number: 4,},{type: "Русский",name: "py",onlay: "俄语",active: false,number: 5,},{type: "한국어",name: "hy",onlay: "韩语",active: false,number: 6,},{type: "Japanese",name: "jp",onlay: "日语",active: false,number: 7,},],
QrSearch(num = "qweasd") {qrNuber({ number: num }).then((res) => {if (res.code === 200) {try {let tem = JSON.parse(res.msg);uni.setStorageSync("deviceTitle", tem);this.loadSavedLanguage();} catch (e) {console.log("二维码内容不是JSON格式,直接存储字符串:", temp);}}});},