背景:

项目引入多语言后发现还有个别地方没有翻译完全, 直接使用i18n 的方法来写的话会直接报错, 比如:
1. router.js 中默认路由的title(也可以在渲染menu或tag 时使用{{$t(xxx)}}
2. index.html 中的 title
3. 一些js方法库中的多语言

解决办法:

示例代码

// lang/index.js
import Vue from "vue"
import ElementUI from "element-ui"
import VueI18n from "vue-i18n"
// elment-ui 
import locale from "element-ui/lib/locale"
import zhLocale from "element-ui/lib/locale/lang/zh-CN"
import enLocale from "element-ui/lib/locale/lang/en"
vxe-table
import VXEzhCN from "vxe-table/lib/locale/lang/zh-CN"
import VXEenUS from "vxe-table/lib/locale/lang/en-US"
// 自己的多语言文件
import zh from "./zh"
import en from "./en"

Vue.use(VueI18n)

const messages = {
    "zh-CN": {
        ...zh,
        ...zhLocale,
        ...VXEzhCN,
    },
    "en-US": {
        ...en,
        ...enLocale,
        ...VXEenUS,
    }
}

const i18n = new VueI18n({
    messages,
    fallbackLocale: "zh-CN", // 匹配不到时默认的语言
    silentTranslationWarn: true,  // 控制台的warning
    locale: localStorage.getItem("language") || "zh-CN", // set locale
})

locale.use(ElementUI, {
    i18n: (key, value) => i18n.t(key, value),
})

// *** 
// 非 vue 文件中使用这个方法
const translate = (localeKey) => {
    const locale = localStorage.getItem("language") || "zh-CN"
    const hasKey = i18n.te(localeKey, locale)  // 使用i18n的 te 方法来检查是否能够匹配到对应键值
    const translatedStr = i18n.t(localeKey) 
    if (hasKey) {
        return translatedStr
    }
    return localeKey
}

export { i18n, messages, translate }

// 使用  例如: router.js
import Vue from "vue"
import Router from "vue-router"
import Layout from "@/layout"
import { translate as $t } from "@/lang"
export const constantRoutes = [
	{
        path: "/home",
        name: "home",
        component: () => import("@/views/home/index"),
        meta: { title: $t("route.title.home"), icon: "home", showInMenu: true, affix: true, tabIndex: 0 },
    },
]

const createRouter = () =>
    new Router({
        base: "/bp/",
        mode: "history", // require service support
        scrollBehavior: () => ({ y: 0 }),
        routes: constantRoutes,
    })

const router = createRouter()

export default router

Logo

前往低代码交流专区

更多推荐