vue3 | echarts公共组件简易封装

组件模板

<template>
  <div ref="canvasEl" :style="myStyle"></div>
</template>

<script setup lang="ts">
import { ref, watch, shallowRef, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts';

interface ChartProps {
  myStyle?: any
  loading?: boolean
  dataEmptyFlag?: boolean
  options: any
}

const props = withDefaults(defineProps<ChartProps>(), {
  myStyle: {
    width: '100%',
    height: '350px'
  },
  loading: false,
  dataEmptyFlag: false,
  options: {
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: []
  }
})

const canvasEl = shallowRef()
const myChart = shallowRef()

const resizeFn = () => {
  myChart.value?.resize()
}

const handleSetOptions = (options) => {
  const defaultOpt = {
    grid:{
      borderWidth: 0,
      top:'10%',
      bottom:'10%',
      left:'10%'
    },
    color: ['#DA5874', '#4FC5EA', '#3F58D2', '#FFB11A', '#3FD251', '#F86846', '#BFBFBF', '#78C446', '#5ED8A9', '#605AD8', '#8F55E7'],
    tooltip: {
      trigger: 'item',
      formatter: '{b} : {c}'
    },
    ...options
  }
  myChart.value.setOption(defaultOpt)
}

onMounted(() => {
  myChart.value = echarts.init(canvasEl.value)
  handleSetOptions(props.options)
  window.addEventListener('resize', resizeFn)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeFn)
  myChart.value?.dispose()
  myChart.value = null
})

watch(() => props?.options, (val) => {
  if (myChart) {
    handleSetOptions(val)
  }
})
</script>

使用方法

<myECharts :myStyle="{ height: '400px' }" :options="options">myECharts>

你可能感兴趣的:(echarts,javascript,前端)