perf: 优化 JSON 序列化无法处理函数的问题

This commit is contained in:
奔跑的面条 2023-01-09 11:25:03 +08:00
parent 5e0baa4923
commit 462a613bd3
7 changed files with 51 additions and 18 deletions

View File

@ -291,3 +291,37 @@ export const setKeyboardDressShow = (keyCode?: number) => {
} }
} }
/**
* * JSON序列化 undefined
* @param data
*/
export const JSONStringify = (data: object) => {
return JSON.stringify(
data,
(key, val) => {
// 处理函数丢失问题
if (typeof val === 'function') {
return `${val}`
}
// 处理 undefined 丢失问题
if (typeof val === 'undefined') {
return 'undefined'
}
return val
},
2
)
}
/**
* * JSON反序列化 undefined
* @param data
*/
export const JSONParse = (data: string) => {
return JSON.parse(data, (k, v) => {
if (typeof v === 'string' && v.indexOf && (v.indexOf('function') > -1 || v.indexOf('=>') > -1)) {
return eval(`(function(){return ${v}})()`)
}
return v
})
}

View File

@ -41,12 +41,13 @@ import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore
import { EditCanvasTypeEnum } from '@/store/modules/chartEditStore/chartEditStore.d' import { EditCanvasTypeEnum } from '@/store/modules/chartEditStore/chartEditStore.d'
import { ChartModeEnum } from '@/store/modules/chartLayoutStore/chartLayoutStore.d' import { ChartModeEnum } from '@/store/modules/chartLayoutStore/chartLayoutStore.d'
import { useChartLayoutStore } from '@/store/modules/chartLayoutStore/chartLayoutStore' import { useChartLayoutStore } from '@/store/modules/chartLayoutStore/chartLayoutStore'
import { componentInstall, loadingStart, loadingFinish, loadingError } from '@/utils' import { componentInstall, loadingStart, loadingFinish, loadingError, JSONStringify } from '@/utils'
import { DragKeyEnum } from '@/enums/editPageEnum' import { DragKeyEnum } from '@/enums/editPageEnum'
import { createComponent } from '@/packages' import { createComponent } from '@/packages'
import { ConfigType, CreateComponentType } from '@/packages/index.d' import { ConfigType, CreateComponentType } from '@/packages/index.d'
import { fetchConfigComponent, fetchChartComponent } from '@/packages/index' import { fetchConfigComponent, fetchChartComponent } from '@/packages/index'
import omit from 'lodash/omit' import omit from 'lodash/omit'
const chartEditStore = useChartEditStore() const chartEditStore = useChartEditStore()
defineProps({ defineProps({
@ -70,7 +71,7 @@ const dragStartHandle = (e: DragEvent, item: ConfigType) => {
componentInstall(item.chartKey, fetchChartComponent(item)) componentInstall(item.chartKey, fetchChartComponent(item))
componentInstall(item.conKey, fetchConfigComponent(item)) componentInstall(item.conKey, fetchConfigComponent(item))
// //
e!.dataTransfer!.setData(DragKeyEnum.DRAG_KEY, JSON.stringify(omit(item, ['image']))) e!.dataTransfer!.setData(DragKeyEnum.DRAG_KEY, JSONStringify(omit(item, ['image'])))
// //
chartEditStore.setEditCanvas(EditCanvasTypeEnum.IS_CREATE, true) chartEditStore.setEditCanvas(EditCanvasTypeEnum.IS_CREATE, true)
} }

View File

@ -1,7 +1,7 @@
import { ref, toRef, nextTick } from 'vue' import { ref, toRef, nextTick } from 'vue'
import { UploadCustomRequestOptions } from 'naive-ui' import { UploadCustomRequestOptions } from 'naive-ui'
import { FileTypeEnum } from '@/enums/fileTypeEnum' import { FileTypeEnum } from '@/enums/fileTypeEnum'
import { readFile, downloadTextFile } from '@/utils' import { readFile, downloadTextFile, JSONStringify, JSONParse } from '@/utils'
export const useFile = (targetData: any) => { export const useFile = (targetData: any) => {
const uploadFileListRef = ref() const uploadFileListRef = ref()
@ -23,7 +23,7 @@ export const useFile = (targetData: any) => {
nextTick(() => { nextTick(() => {
if (file.file) { if (file.file) {
readFile(file.file).then((fileData: any) => { readFile(file.file).then((fileData: any) => {
targetData.value.option.dataset = JSON.parse(fileData) targetData.value.option.dataset = JSONParse(fileData)
}) })
} else { } else {
window['$message'].error('导入数据失败,请稍后重试或联系管理员!') window['$message'].error('导入数据失败,请稍后重试或联系管理员!')
@ -35,7 +35,7 @@ export const useFile = (targetData: any) => {
const download = () => { const download = () => {
try { try {
window['$message'].success('下载中,请耐心等待...') window['$message'].success('下载中,请耐心等待...')
downloadTextFile(JSON.stringify(targetData.value.option.dataset), undefined, 'json') downloadTextFile(JSONStringify(targetData.value.option.dataset), undefined, 'json')
} catch (error) { } catch (error) {
window['$message'].error('下载失败,数据错误!') window['$message'].error('下载失败,数据错误!')
} }

View File

@ -1,7 +1,7 @@
import { ref, nextTick } from 'vue' import { ref, nextTick } from 'vue'
import { UploadCustomRequestOptions } from 'naive-ui' import { UploadCustomRequestOptions } from 'naive-ui'
import { FileTypeEnum } from '@/enums/fileTypeEnum' import { FileTypeEnum } from '@/enums/fileTypeEnum'
import { readFile, goDialog } from '@/utils' import { readFile, goDialog, JSONParse } from '@/utils'
import { useSync } from '@/views/chart/hooks/useSync.hook' import { useSync } from '@/views/chart/hooks/useSync.hook'
export const useFile = () => { export const useFile = () => {
@ -34,7 +34,7 @@ export const useFile = () => {
// 新增 // 新增
onPositiveCallback: async () => { onPositiveCallback: async () => {
try { try {
fileData = JSON.parse(fileData) fileData = JSONParse(fileData)
await updateComponent(fileData, false, true) await updateComponent(fileData, false, true)
window['$message'].success('导入成功!') window['$message'].success('导入成功!')
} catch (error) { } catch (error) {
@ -45,7 +45,7 @@ export const useFile = () => {
// 覆盖 // 覆盖
onNegativeCallback: async () => { onNegativeCallback: async () => {
try { try {
fileData = JSON.parse(fileData) fileData = JSONParse(fileData)
await updateComponent(fileData, true, true) await updateComponent(fileData, true, true)
window['$message'].success('导入成功!') window['$message'].success('导入成功!')
} catch (error) { } catch (error) {

View File

@ -1,5 +1,5 @@
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore' import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { canvasCut, downloadTextFile } from '@/utils' import { canvasCut, downloadTextFile, JSONStringify } from '@/utils'
const chartEditStore = useChartEditStore() const chartEditStore = useChartEditStore()
// 导出 // 导出
@ -9,9 +9,7 @@ export const exportHandle = () => {
// 导出数据 // 导出数据
downloadTextFile( downloadTextFile(
JSON.stringify(chartEditStore.getStorageInfo || [], (k, v) => { JSONStringify(chartEditStore.getStorageInfo || []),
return v === undefined ? null : v
}),
undefined, undefined,
'json' 'json'
) )

View File

@ -6,7 +6,7 @@ import { CreateComponentType, CreateComponentGroupType, PickCreateComponentType
import { useContextMenu } from '@/views/chart/hooks/useContextMenu.hook' import { useContextMenu } from '@/views/chart/hooks/useContextMenu.hook'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore' import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { EditCanvasTypeEnum } from '@/store/modules/chartEditStore/chartEditStore.d' import { EditCanvasTypeEnum } from '@/store/modules/chartEditStore/chartEditStore.d'
import { loadingStart, loadingFinish, loadingError, setComponentPosition } from '@/utils' import { loadingStart, loadingFinish, loadingError, setComponentPosition, JSONParse } from '@/utils'
import { throttle, cloneDeep } from 'lodash' import { throttle, cloneDeep } from 'lodash'
const chartEditStore = useChartEditStore() const chartEditStore = useChartEditStore()
@ -28,7 +28,7 @@ export const dragHandle = async (e: DragEvent) => {
// 修改状态 // 修改状态
chartEditStore.setEditCanvas(EditCanvasTypeEnum.IS_CREATE, false) chartEditStore.setEditCanvas(EditCanvasTypeEnum.IS_CREATE, false)
const dropData: Exclude<ConfigType, ['image']> = JSON.parse(drayDataString) const dropData: Exclude<ConfigType, ['image']> = JSONParse(drayDataString)
// 创建新图表组件 // 创建新图表组件
let newComponent: CreateComponentType = await createComponent(dropData) let newComponent: CreateComponentType = await createComponent(dropData)

View File

@ -38,7 +38,7 @@ import { MonacoEditor } from '@/components/Pages/MonacoEditor'
import { SavePageEnum } from '@/enums/editPageEnum' import { SavePageEnum } from '@/enums/editPageEnum'
import { getSessionStorageInfo } from '../preview/utils' import { getSessionStorageInfo } from '../preview/utils'
import type { ChartEditStorageType } from '../preview/index.d' import type { ChartEditStorageType } from '../preview/index.d'
import { setSessionStorage } from '@/utils' import { setSessionStorage, JSONStringify, JSONParse } from '@/utils'
import { StorageEnum } from '@/enums/storageEnum' import { StorageEnum } from '@/enums/storageEnum'
import { icon } from '@/plugins' import { icon } from '@/plugins'
@ -48,7 +48,7 @@ const content = ref('')
// sessionStorage // sessionStorage
async function getDataBySession() { async function getDataBySession() {
const localStorageInfo: ChartEditStorageType = await getSessionStorageInfo() as unknown as ChartEditStorageType const localStorageInfo: ChartEditStorageType = await getSessionStorageInfo() as unknown as ChartEditStorageType
content.value = JSON.stringify(localStorageInfo, undefined, 2) content.value = JSONStringify(localStorageInfo)
} }
setTimeout(getDataBySession) setTimeout(getDataBySession)
@ -72,7 +72,7 @@ async function importJSON() {
// [JSONJSONCtrl+S ] // [JSONJSONCtrl+S ]
window.opener.addEventListener(SavePageEnum.CHART, (e: any) => { window.opener.addEventListener(SavePageEnum.CHART, (e: any) => {
setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, [e.detail]) setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, [e.detail])
content.value = JSON.stringify(e.detail, undefined, 2) content.value = JSONStringify(e.detail)
}) })
// + => // + =>
@ -90,7 +90,7 @@ async function updateSync() {
return window['$message'].error('源窗口已关闭,视图同步失败') return window['$message'].error('源窗口已关闭,视图同步失败')
} }
try { try {
const detail = JSON.parse(content.value) const detail = JSONParse(content.value)
delete detail.id delete detail.id
// id // id
window.opener.dispatchEvent(new CustomEvent(SavePageEnum.JSON, { detail })) window.opener.dispatchEvent(new CustomEvent(SavePageEnum.JSON, { detail }))