useLifeHandler.hook.ts 2.1 KB

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