把echarts封装成公共的组件
中文官网地址:Apache ECharts
以柱状图为例
npm install echarts --save
//EchartsBar.vue子组件
<template>
<div class="barChart" ref="main" :style="{ height: height }"></div>
</template>
<script>
import * as echarts from "echarts";
export default {
name: "barChart",
props: {
chartData: {
type: Object,
default: () => ({}),
},
height: {
type: String,
default: "300px",
},
},
data() {
return {
myChart: null,
};
},
mounted() {
this.myChart = echarts.init(this.$refs.main);
},
watch: {
chartData: {
handler(val) {
this.resData = val;
this.$nextTick(function () {
//页面加载完成后执行
this.myEcharts();
});
},
immediate: true,
deep: true,
},
},
methods: {
myEcharts() {
//配置图表
var option = {
title: {
text: 'World Population'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
legend: { },
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
max: this.resData.barMax,
min: 0,
type: 'value',
boundaryGap: [0, 0.01]
},
yAxis: {
type: 'category',
data: this.resData.xData
},
series: [
{
name: '2011',
type: 'bar',
data: this.resData.yDataAvg
},
{
name: '2012',
type: 'bar',
data: this.resData.yDataMe
}
]
};
this.myChart.setOption(option);
},
},
};
</script>
<style scoped lang="scss">
.barChart {
width: 100%;
}
</style>
//父组件
home.vue
<template>
<EchartsBar :chartData="barData" :height="'266px'" />
</template>
<script>
import EchartsBar from "./EchartsBar.vue";
components: {
EchartsBar,
},
data(){
return {
barData: {
xData: [],
yDataAvg: [],
yDataMe: [],
gridtop: "0%",
gridbottom: "6%",
shadowOffsetY: -20,
barMax: 200,
},
}
}
</script>