在 Vue3 中封装一个 echarts 方法,可以按照以下步骤:

  1. 安装 echarts
npm i echarts -S
  1. 在组件中引入 echarts
import echarts from 'echarts'
  1. 封装 echarts 方法
<template>
  <div :id="id" :style="{ width: width + 'px', height: height + 'px' }"></div>
</template>

<script>
export default {
  props: {
    width: {
      type: Number,
      default: 600
    },
    height: {
      type: Number,
      default: 400
    },
    option: {
      type: Object,
      default: () => {}
    },
    id: {
      type: String,
      default: 'chart'
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    initChart() {
      const chart = echarts.init(document.getElementById(this.id))
      chart.setOption(this.option)
      window.addEventListener('resize', () => {
        chart.resize()
      })
    }
  }
}
</script>
  1. 在组件中使用封装的 echarts 方法
<template>
  <Echarts :width="600" :height="400" :option="option" id="chart"></Echarts>
</template>

<script>
import Echarts from '@/components/Echarts'

export default {
  components: {
    Echarts
  },
  data() {
    return {
      option: {
        // echarts option
      }
    }
  }
}
</script>

这样,我们就可以通过传入宽高、option 和 id 来生成 echarts 图表了。

在vue3中封装一个echarts方法传入宽高opitionid就可以生成图表

原文地址: https://www.cveoy.top/t/topic/bi37 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录