echarts组件封装

my-echart文件

<template>
  <div ref="elRef" :style="styles"></div>
</template>

<script setup>
import { ref, unref, computed, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import { debounce } from "lodash-es";

import { isString } from "@/utils/is";

const props = defineProps({
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "100%",
  },
  options: {
    type: Object,
    required: true,
  },
});
const styles = computed(() => {
  const width = isString(props.width) ? props.width : `${props.width}px`;
  const height = isString(props.height) ? props.height : `${props.height}px`;

  return {
    width,
    height,
  };
});
const elRef = ref();
let echartRef = null;

function init() {
  if (unref(elRef) && props.options) {
    echartRef = echarts.init(unref(elRef));
    echartRef?.setOption(props.options);
  }
}
const resizeHandler = debounce(() => {
  if (echartRef) {
    echartRef.resize();
  }
}, 100);
onMounted(() => {
  init();
  window.addEventListener("resize", resizeHandler);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeHandler);
});
</script>

<style lang="less" scoped></style>

使用

<MyEchart :options="lineEchartOption"></MyEchart>

import MyEchart from "@/components/my-echart/my-echart.vue";

const lineEchartOption = {
  xAxis: {
    type: "category",
    data: [
      "2023-10-21",
      "2023-10-22",
      "2023-10-23",
      "2023-10-24",
      "2023-10-25",
      "2023-10-26",
      "2023-10-27",
    ],
  },
  yAxis: {
    type: "value",
  },
  grid: {
    top: 20,
    left: 50,
    right: 10,
    bottom: 26,
  },
  series: [
    {
      data: [60, 40, 80, 100, 60, 80, 40],
      type: "line",
      lineStyle: {
        color: "#0170FE",
      },
      areaStyle: {
        // 开启渐变色
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: "rgba(0, 128, 255, 0.2)", // 渐变起始颜色
          },
          {
            offset: 1,
            color: "rgba(0, 128, 255, 0.05)", // 渐变结束颜
          },
        ]),
      },
    },
  ],
};

注意:宽高

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值