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)", // 渐变结束颜
},
]),
},
},
],
};
注意:宽高