封装echarts,实现高宽自适应和随窗口大小变化resize

70 阅读1分钟

核心是监听父组件传入的 width、height、option 的变化并 resize

//template
  <div :style="style" ref="chartRef"></div>
//script setup
import { ref,toRefs, computed, nextTick, watch } from 'vue';
import * as echarts from 'echarts';
import { useEventListener } from '@vueuse/core';
const props = defineProps({
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "100%",
  },
  option: {
    type: Object,
    default: null,
  },
});
const { height, width, option } = toRefs(props);
const style = computed(() => {
  return {
    width: width.value,
    height: height.value,
  };
});
//拿到DOM
const chartRef = ref(null);

//传入的option对象的引用地址改变重新setOption
watch(option, () => {
  myChart.setOption(option.value);
});

//传入的高宽改变会resize
watch([width, height], () => {
  myChart.resize();
});

//窗口的高宽改变会resize
useEventListener(window, 'resize', () => {
  myChart.resize();
});
let myChart;
/* 
这里用nextTick而非onMounted是因为若chart作为子组件
会先于父组件mounted,拿不到父组件的实际宽高
100%便会被解析为100px
*/
nextTick(() => {
  myChart = echarts.init(chartRef.value);
  myChart.setOption(option.value);
});

父组件中使用

<MyEcharts :width="width" :height="height" :option="option"></MyEcharts>

OK了家人们!