Skip to content

Commit

Permalink
使用compositionAPi重构国际化mixin
Browse files Browse the repository at this point in the history
  • Loading branch information
yc910920 committed Feb 22, 2022
1 parent a65d7b7 commit ae12c6a
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/config-provider/useConfig.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/* eslint-disable no-console */
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.value,
classPrefix,
};
}

0 comments on commit ae12c6a

Please sign in to comment.