index.vue 2.31 KB
<template>
  <v-chart
    ref="vChartRef"
    :init-options="initOptions"
    :theme="themeColor"
    :option="option"
    :manual-update="isPreview()"
    :update-options="{
      replaceMerge: replaceMergeArr
    }"
    autoresize
  ></v-chart>
</template>

<script setup lang="ts">
import { ref, computed, PropType, watch } from 'vue'
import VChart from 'vue-echarts'
import { useCanvasInitOptions } from '@/hooks/useCanvasInitOptions.hook'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart } from 'echarts/charts'
import config from './config'
import { mergeTheme } from '@/packages/public/chart'
import { useChartDataFetch } from '@/hooks'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { isPreview } from '@/utils'
import { DatasetComponent, GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'

const props = defineProps({
  themeSetting: {
    type: Object,
    required: true
  },
  themeColor: {
    type: Object,
    required: true
  },
  chartConfig: {
    type: Object as PropType<config>,
    required: true
  }
})

const initOptions = useCanvasInitOptions(eval('(' + props.chartConfig.option.dataset + ')'), props.themeSetting)

use([DatasetComponent, CanvasRenderer, BarChart, GridComponent, TooltipComponent, LegendComponent])

const replaceMergeArr = ref<string[]>()

const option = computed(() => {
  return mergeTheme(eval('(' + props.chartConfig.option.dataset + ')'), props.themeSetting, [])
})

const { vChartRef } = useChartDataFetch(props.chartConfig, useChartEditStore)

const updateVChart = (dataset: object) => {
  new Promise(resolve => {
    setTimeout(() => {
      resolve(
        vChartRef.value?.setOption(
          {
            ...dataset
          },
          {
            notMerge: true
          }
        )
      )
    }, 100)
  })
}

watch(
  () => props.chartConfig.option.dataset,
  newValue => {
    try {
      //嵌套字符串使用JSON.parse会报错,这里使用eval函数
      updateVChart(eval('(' + newValue + ')'))
    } catch (e) {
      console.error(
        `文件位置:src\\packages\\components\\external\\InformationsMores\\CustomEcharts\\index.vue`,
        '错误信息:您的json格式有误'
      )
    }
  },
  {
    immediate: true,
    deep: true
  }
)
</script>