【vue3基础】Echarts的封装和自适应功能

408 阅读1分钟

项目中经常会用到 Echarts 来展示统计数据,但是 Echarts 的图表的大小自适应动态的内容需要自己手动触发事件。

1. 引入 Echarts

npm install echarts --save

2. 引入封装的 Echart 组件

main.js 文件中引入

// 全局提供echarts,以便在任何地方都可以使用new echarts
import * as echarts from 'echarts'
app.provide('echarts', echarts)
// 引入echarts组件(自己封装的组件)
import Echart from '@/components/Echart.vue'
// 注册全局组件
app.component('Echart', Echart)

3. 封装 Echart 组件

<template>
  <div :id="id" :style="style"></div>
</template>
<script setup>
import _ from 'lodash';
const echarts = inject('echarts')
const props = defineProps({
  options: {
    type: Object,
    default: () => ({}),
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  id: {
    type: String,
    default: new Date().getTime() + Math.random().toString(32).slice(2, 10) // id可以自己随机定义
  }
})

let style = computed(() => ({
  width: props.width,
  height: props.height
}))

let chart

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
})

const resizeChart = _.debounce(() => {
  chart && chart.resize()
}, 500)


const initChart = () => {
  nextTick(() => {
    chart = echarts.init(document.getElementById(props.id))
    chart.setOption(props.options, true)
  })
}
</script>

4. 页面中使用

<template>
  <Echart id="myChart" :width="width" :height="height" :options="options" />
</template>

<script setup>
let width = ref('50%')
let height = ref('50%')

// const echarts = inject('echarts')  // 如果需要用到 new echarts 时候的引入

let options = computed(() => {
  return {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [120, 200, 150, 80, 70, 110, 130],
        type: 'bar'
      }
    ]
  }
})
</script>

如果 widthheight 是固定值 px 情况下是不会改变的,因为屏幕变动不会影响固定值的改变。