vue3 组合式api 封装echarts,并自适应大小

<template>
  <div ref="chartContainer" :style="chartStyle"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  options: {
    type: Object,
    required: true,
    default: () => ({
      title: {
        text: 'ECharts 示例'
      },
      grid: {
        left: 0,
        right: 0,
        // 如果需要去除上下padding,可以设置top和bottom
        // top: 0,
        // bottom: 0,
        containLabel: true // 确保标签也在grid区域内
      },
      tooltip: {},
      xAxis: {
        type: 'category',
        nameLocation: 'center',
        axisTick: {
          show: false,
          alignWithLabel: true
        },
        data: ['1', '2', '3', '4', '5', '6']
      },
      yAxis: {},
      series: [
        {
          name: '销量',
          type: 'line',
          data: [5, 20, 36, 10, 10, 20]
        }
      ]
    })
  },
  style: {
    default: () => ({
      width: '100%',
      height: '100%'
    })
  }
})

const chartContainer = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  const container = chartContainer.value
  if (container) {
    chartInstance = echarts.init(container)
    chartInstance.setOption(props.options)

    // 监听窗口大小变化
    window.addEventListener('resize', resizeChart)
  }
}

// 调整图表大小
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 销毁图表实例
const destroyChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
    window.removeEventListener('resize', resizeChart)
  }
}

onMounted(() => {
  initChart()
})

onBeforeUnmount(() => {
  destroyChart()
})

// 暴露给模板的响应式数据
const chartStyle = props.style
</script>

<style scoped>
/* 样式可以根据需要自定义 */
</style>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容