安装echarts依赖
npm install echarts --save
代码实现
封装Echarts组件Echarts.vue:
<template>
<div :id="id" :style="styleObject" />
</template>
<script>
import * as echarts from "echarts";
import "echarts/lib/chart/pie";
import "echarts/lib/component/title";
import { setTimeout } from "timers";
export default {
props: {
styleObject: {
type: Object,
default: () => ({ height: "300px", width: "100%" }),
},
option: {
type: Object,
default: () => {},
},
id: {
type: String,
default: "echart2020" + ("_" + Math.random()).replace(".", "_"),
},
},
data: function () {
return {
resizeTimer: null,
myChart: null,
};
},
methods: {
refersh() {
setTimeout(() => {
this.initPie(this.id);
}, 500);
},
initPie(id) {
const { option } = this;
let chart = echarts.getInstanceByDom(window.document.getElementById(id));
if (chart === undefined) {
chart = echarts.init(window.document.getElementById(id));
}
chart.setOption(option);
this.myChart = chart;
},
resizePie() {
if (this.myChart) {
this.myChart.resize();
}
},
refreshData(data) {
if (this.myChart) {
this.myChart.setOption(data);
}
},
},
created() {},
watch: {
option: {
handler() {
this.refersh();
},
immediate: true,
deep: true,
},
},
mounted() {
this.refersh();
let _this = this;
window.addEventListener("resize", function () {
if (_this.resizeTimer) {
clearTimeout(_this.resizeTimer);
}
_this.resizeTimer = setTimeout(function () {
if (_this.myChart !== undefined) {
_this.myChart.resize();
}
}, 100);
});
},
};
</script>
Echarts数据pieData.js:
export default {
title: {
text: '未来一周气温变化',
},
tooltip: {
trigger: 'axis'
},
legend: {
data: ['最高气温', '最低气温']
},
toolbox: {
show: true,
feature: {
mark: { show: true },
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
calculable: true,
xAxis: [{
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
}],
yAxis: [{
type: 'value',
axisLabel: {
formatter: '{value} °C'
}
}],
series: [{
name: '最高气温',
type: 'line',
data: [11, 11, 15, 13, 12, 13, 10],
markPoint: {
data: [
{ type: 'max', name: '最大值' },
{ type: 'min', name: '最小值' }
]
},
markLine: {
data: [
{ type: 'average', name: '平均值' }
]
}
},
{
name: '最低气温',
type: 'line',
data: [1, -2, 2, 5, 3, 2, 0],
markPoint: {
data: [
{ name: '周最低', value: -2, xAxis: 1, yAxis: -1.5 }
]
},
markLine: {
data: [
{ type: 'average', name: '平均值' }
]
}
}
]
}
使用Echarts组件:
<template>
<div>
<Echarts :option="pieData" id="pieData" ref="pieData"></Echarts>
</div>
</template>
<script>
import Echarts from "./Echarts.vue";
import pieData from "./pieData";
export default {
data: function () {
return {
pieData: pieData,
};
},
components: {
Echarts,
},
created() {},
methods: {},
};
</script>
效果如下:
|