middle-admin-ant/src/utils/i18n.js

79 lines
2.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Vue from 'vue' // 引入 vue
import VueI18n from 'vue-i18n' // 引入 vue-i18n
import routesI18n from '@/router/i18n' // 路由国际化
import './Objects' // 引入对象扩展
import {getI18nKey} from '@/utils/routerUtil' // 引入路由工具
/**
* 创建 i18n 配置
* @param locale 本地化语言
* @param fallback 回退语言
* @returns {VueI18n}
*/
function initI18n(locale, fallback) { // 初始化 i18n
Vue.use(VueI18n) // 使用 vue-i18n
let i18nOptions = { // i18n 配置
locale, // 本地化语言
fallbackLocale: fallback, // 回退语言
silentFallbackWarn: true, // 回退语言警告
}
return new VueI18n(i18nOptions) // 创建 i18n 实例
}
/**
* 根据 router options 配置生成 国际化语言
* @param lang
* @param routes
* @param valueKey
* @returns {*}
*/
function generateI18n(lang, routes, valueKey) { // 生成 i18n
routes.forEach(route => { // 遍历路由
let keys = getI18nKey(route.fullPath).split('.') // 获取 i18n key
let value = valueKey === 'path' ? route[valueKey].split('/').filter(item => !item.startsWith(':') && item != '').join('.') : route[valueKey] // 获取 i18n valueKey 对应的值
lang.assignProps(keys, value) // 给 lang 对象注入属性
if (route.children) { // 如果有子路由
generateI18n(lang, route.children, valueKey) // 递归
}
})
return lang
}
/**
* 格式化 router.options.routes生成 fullPath
* @param routes
* @param parentPath
*/
function formatFullPath(routes, parentPath = '') { // 格式化 fullPath
routes.forEach(route => { // 遍历路由
let isFullPath = route.path.substring(0, 1) === '/' // 判断是否是全路径
route.fullPath = isFullPath ? route.path : (parentPath === '/' ? parentPath + route.path : parentPath + '/' + route.path) // 生成 fullPath
if (route.children) { // 如果有子路由
formatFullPath(route.children, route.fullPath) // 递归
}
})
}
/**
* 从路由提取国际化数据
* @param i18n
* @param routes
*/
function mergeI18nFromRoutes(i18n, routes) { // 从路由提取国际化数据
formatFullPath(routes) // 格式化 fullPath
const CN = generateI18n(new Object(), routes, 'name') // 生成中文国际化
const US = generateI18n(new Object(), routes, 'path') // 生成英文国际化
i18n.mergeLocaleMessage('CN', CN) // 合并中文国际化
i18n.mergeLocaleMessage('US', US) // 合并英文国际化
const messages = routesI18n.messages // 获取路由国际化
Object.keys(messages).forEach(lang => { // 遍历路由国际化
i18n.mergeLocaleMessage(lang, messages[lang]) // 合并路由国际化
})
}
export { // 导出
initI18n, // 初始化 i18n 国际化
mergeI18nFromRoutes, // 从路由提取国际化数据
formatFullPath // 格式化 fullPath
}