feat: 组件生命周期事件

This commit is contained in:
潘潘
2022-10-11 18:31:29 +08:00
parent c84f6d9c33
commit 92339dae28
12 changed files with 348 additions and 6 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
export * from '@/hooks/useTheme.hook'
export * from '@/hooks/usePreviewScale.hook'
export * from '@/hooks/useCode.hook'
export * from '@/hooks/useChartDataFetch.hook'
export * from '@/hooks/useChartDataFetch.hook'
export * from '@/hooks/useLifeHandler.hook'
+48
View File
@@ -0,0 +1,48 @@
import { CreateComponentType, EventLife } from '@/packages/index.d'
import * as echarts from 'echarts'
// 所有图表组件集合对象
const components: {[K in string]?: any} = {};
// 项目提供的npm 包变量
export const npmPkgs = { echarts }
export const useLifeHandler = (chartConfig: CreateComponentType) => {
const events = chartConfig.events || {}
// 生成生命周期事件
const lifeEvents = {
[EventLife.BEFORE_MOUNT] (e:any) {
// 存储组件
components[chartConfig.id] = e.component
const fnStr = (events[EventLife.BEFORE_MOUNT] || '').trim()
generateFunc(fnStr, e)
},
[EventLife.MOUNTED] (e:any){
const fnStr = (events[EventLife.MOUNTED] || '').trim()
generateFunc(fnStr, e)
},
}
return lifeEvents
}
/**
*
* @param fnStr 用户方法体代码
* @param e 执行生命周期的动态组件实例
*/
function generateFunc(fnStr: string, e: any){
try {
Function(`
"use strict";
return (
async function(e, components, node_modules){
const {${Object.keys(npmPkgs).join()}} = node_modules;
${fnStr}
}
)`)().bind(e?.component)
// 便于拷贝echarts示例时设置option 的formatter等相关内容
(e, components, npmPkgs);
} catch (error) {
console.error(error)
}
}