-
Notifications
You must be signed in to change notification settings - Fork 503
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #356 from yc910920/develop
使用compositionAPi重构国际化mixin
- Loading branch information
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import { computed, inject, Ref } from 'vue'; | ||
import defaultConfig from './zh_CN_config'; | ||
|
||
export * from './type'; | ||
|
||
/** | ||
* receive component global config | ||
* @param componentName | ||
* @returns {t, global} | ||
*/ | ||
export default function useConfig<T>(componentName: string) { | ||
const global = computed(() => { | ||
const globalConfig = inject('globalConfig', {}); | ||
const defaultConfigData = defaultConfig[componentName]; | ||
if (globalConfig && globalConfig[componentName]) { | ||
return { | ||
...defaultConfigData, | ||
...globalConfig[componentName], | ||
}; | ||
} | ||
return defaultConfigData; | ||
}); | ||
|
||
// 处理正则表达式 | ||
const t = function <T>(pattern: T, data?: Record<string, string | number>) { | ||
if (typeof pattern === 'string') { | ||
if (!data) return pattern; | ||
const regular = /\{\s*([\w-]+)\s*\}/g; | ||
const translated = pattern.replace(regular, (match, key) => { | ||
if (data) { | ||
return String(data[key]); | ||
} | ||
return ''; | ||
}); | ||
return translated; | ||
} | ||
if (typeof pattern === 'function') { | ||
return pattern(data); | ||
} | ||
return ''; | ||
}; | ||
|
||
const classPrefix = 't'; | ||
return { | ||
t, | ||
global, | ||
classPrefix, | ||
}; | ||
} |