父组件
<template>
<div class="echartsBox">
<el-row :gutter="20">
<el-col :xs="24" :sm="24" :lg="12">
<Echarts
:echartStyle="echartStyle"
:titleText="title"
:legend="legend"
:dataY="dataY"
:dataX="dataX"
id="echartOne"
>
</Echarts>
</el-col>
<el-col :xs="24" :sm="24" :lg="12">
<Echarts
:echartStyle="echartStyle"
:titleText="title"
:legend="legend"
:dataY="dataYTwo"
:dataX="dataX"
id="echartTwo"
>
</Echarts>
</el-col>
</el-row>
</div>
</template>
<script>
import Echarts from "@/components/common/Echarts";
export default {
components: {
Echarts,
},
data() {
return {
echartStyle: {
height: "",
},
title: "数据统计",
legend: ["数量一", "数量二"],
dataX: [
"2019/03/01",
"2019/03/02",
"2019/03/03",
"2019/03/04",
"2019/03/05",
"2019/03/06",
"2019/03/07",
],
dataY: [
{
name: "数量一",
type: "line",
stack: "总量",
data: [120, 132, 101, 134, 90, 230, 210],
},
{
name: "数量二",
type: "line",
stack: "总量",
data: [220, 182, 191, 234, 290, 330, 310],
},
],
dataYTwo: [],
};
},
created() {
this.echartStyle.height = 300 + "px";
},
};
</script>
<style lang="less" scoped>
.echartsBox {
padding: 24px;
.item {
background: #fff;
}
}
</style>
子组件
<template>
<div :id="id" :style="echartStyle" class="item"></div>
</template>
<script>
import * as echarts from "echarts";
export default {
name: "ECharts",
props: {
echartStyle: {
type: Object,
default() {
return {};
},
},
id: {
type: String,
default: "chart",
},
titleText: {
type: String,
default: "",
},
legend: {
type: Array,
default() {
return [];
},
},
dataY: {
type: Array,
default() {
return [];
},
},
dataX: {
type: Array,
default() {
return [];
},
},
},
data() {
return {
charts: null,
};
},
methods: {
drawLine(id) {
const dom = document.getElementById(id);
if (this.dataY.length === 0) {
dom.innerHTML = "暂无相关图表数据";
dom.style.cssText = "text-align:center; color: #999; border: none;line-height: 300px";
return;
}
this.charts = echarts.init(dom);
let option = {
title: {
left: "center",
text: this.titleText,
},
tooltip: {
trigger: "axis",
},
legend: {
left: "left",
data: this.legend,
},
grid: {
left: "20",
right: "40",
bottom: "20",
containLabel: true,
},
xAxis: {
type: "category",
boundaryGap: false,
data: this.dataX,
},
yAxis: {
type: "value",
},
series: this.dataY,
};
this.charts.setOption(option);
window.addEventListener("resize", () => {
this.charts.resize();
});
},
},
watch: {
option: function () {
this.$nextTick(() => {
this.eChar && this.eChar.setOption(this.option);
});
},
},
created() {},
mounted() {
this.$nextTick(function () {
this.drawLine(this.id);
});
},
update() {
this.$nextTick(() => {
this.eChar && this.eChar.setOption(this.option);
});
},
beforeDestroy() {
this.eChar && this.eChar.destroy && this.eChar.destroy();
},
};
</script>
<style scoped lang="less">
.item {
background: #fff;
margin-bottom: 10px;
}
</style>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3a7db4aceb11a4b2c6a2b2823ed021e5.png)