useLifeHandler.hook.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { CreateComponentType, CreateComponentGroupType } from '@/packages/index.d'
  2. import { EventLife } from '@/enums/eventEnum'
  3. import * as echarts from 'echarts'
  4. // 所有图表组件集合对象
  5. const components: { [K in string]?: any } = {}
  6. // 项目提供的npm 包变量
  7. export const npmPkgs = { echarts }
  8. // 组件事件处理 hook
  9. export const useLifeHandler = (chartConfig: CreateComponentType | CreateComponentGroupType) => {
  10. if (!chartConfig.events) return {}
  11. // 处理基础事件
  12. const baseEvent: { [key: string]: any } = {}
  13. for (const key in chartConfig.events.baseEvent) {
  14. const fnStr: string | undefined = (chartConfig.events.baseEvent as any)[key]
  15. // 动态绑定基础事件
  16. if (fnStr) {
  17. baseEvent[key] = generateBaseFunc(fnStr)
  18. }
  19. }
  20. // 生成生命周期事件
  21. const events = chartConfig.events.advancedEvents || {}
  22. const lifeEvents = {
  23. [EventLife.VNODE_BEFORE_MOUNT](e: any) {
  24. // 存储组件
  25. components[chartConfig.id] = e.component
  26. const fnStr = (events[EventLife.VNODE_BEFORE_MOUNT] || '').trim()
  27. generateFunc(fnStr, e)
  28. },
  29. [EventLife.VNODE_MOUNTED](e: any) {
  30. const fnStr = (events[EventLife.VNODE_MOUNTED] || '').trim()
  31. generateFunc(fnStr, e)
  32. }
  33. }
  34. return { ...baseEvent, ...lifeEvents }
  35. }
  36. /**
  37. * 生成基础函数
  38. * @param fnStr 用户方法体代码
  39. * @param event 鼠标事件
  40. */
  41. export function generateBaseFunc(fnStr: string) {
  42. try {
  43. return new Function(`
  44. return (
  45. async function(mouseEvent){
  46. ${fnStr}
  47. }
  48. )`)()
  49. } catch (error) {
  50. console.error(error)
  51. }
  52. }
  53. /**
  54. * 生成高级函数
  55. * @param fnStr 用户方法体代码
  56. * @param e 执行生命周期的动态组件实例
  57. */
  58. function generateFunc(fnStr: string, e: any) {
  59. try {
  60. // npmPkgs 便于拷贝 echarts 示例时设置option 的formatter等相关内容
  61. Function(`
  62. "use strict";
  63. return (
  64. async function(e, components, node_modules){
  65. const {${Object.keys(npmPkgs).join()}} = node_modules;
  66. ${fnStr}
  67. }
  68. )`)().bind(e?.component)(e, components, npmPkgs)
  69. } catch (error) {
  70. console.error(error)
  71. }
  72. }