index.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { App } from "vue";
  2. import axios from "axios";
  3. let config: object = {};
  4. const { VITE_PUBLIC_PATH } = import.meta.env;
  5. const setConfig = (cfg?: unknown) => {
  6. config = Object.assign(config, cfg);
  7. };
  8. const getConfig = (key?: string): ServerConfigs => {
  9. if (typeof key === "string") {
  10. const arr = key.split(".");
  11. if (arr && arr.length) {
  12. let data = config;
  13. arr.forEach(v => {
  14. if (data && typeof data[v] !== "undefined") {
  15. data = data[v];
  16. } else {
  17. data = null;
  18. }
  19. });
  20. return data;
  21. }
  22. }
  23. return config;
  24. };
  25. /** 获取项目动态全局配置 */
  26. export const getServerConfig = async (app: App): Promise<undefined> => {
  27. app.config.globalProperties.$config = getConfig();
  28. return axios({
  29. method: "get",
  30. url: `${VITE_PUBLIC_PATH}serverConfig.json`
  31. })
  32. .then(({ data: config }) => {
  33. let $config = app.config.globalProperties.$config;
  34. // 自动注入项目配置
  35. if (app && $config && typeof config === "object") {
  36. $config = Object.assign($config, config);
  37. app.config.globalProperties.$config = $config;
  38. // 设置全局配置
  39. setConfig($config);
  40. }
  41. return $config;
  42. })
  43. .catch(() => {
  44. throw "请在public文件夹下添加serverConfig.json配置文件";
  45. });
  46. };
  47. /** 本地响应式存储的命名空间 */
  48. const responsiveStorageNameSpace = () => getConfig().ResponsiveStorageNameSpace;
  49. export { getConfig, setConfig, responsiveStorageNameSpace };