最近在做vue的图表功能,研究了好长时间,现将代码记录下来。
1、vue代码
<template>
<div :class="className" :style="{height:height,width:width}" />
</template>
<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { homeUserMonthChart } from "@/api/home";
export default {
mixins: [resize],
props: {
className: {
type: String,
default: 'chart'
},
width: {
type: String,
default: '99%'
},
height: {
type: String,
default: '350px'
},
autoResize: {
type: Boolean,
default: true
}
},
data() {
return {
chart: null,
lineChartData: {},
expectedData: [],
actualData: [],
monthData:[],
name1: '总用户',
name2: '月活'
}
},
watch: {
chartData: {
deep: true,
handler(val) {
this.setOptions(val)
}
}
},
mounted() {
// 等待一切加载完成后调用初始化方法
this.$nextTick(() => {
//this.initChart()
this.getHomeUserChart();
})
},
beforeDestroy() {
if (!this.chart) {
return
}
this.chart.dispose()
this.chart = null
},
created() {
// this.getHomeUserChart();
},
methods: {
//折线图-总用户与月活 对比
getHomeUserChart(){
homeUserMonthChart(this.queryParams).then(response => {
console.log(response.data);
for (let i = 0;i < response.data.monthData.length;i++) {
var mData=response.data.monthData[i];
this.monthData.push(mData);
}
for (let i = 0;i < response.data.userData.length;i++) {
var mData=response.data.userData[i];
this.actualData.push(mData);
}
for (let i = 0;i < response.data.userAllData.length;i++) {
var mData=response.data.userAllData[i];
this.expectedData.push(mData);
}
//初始化 图形
this.initChart();
});
},
initChart() {
this.chart = echarts.init(this.$el, 'macarons');
this.setOptions();
},
setOptions() {
console.log('x轴分区被初始化');
this.chart.setOption({
xAxis: {
data: this.monthData,
boundaryGap: false,
axisTick: {
show: false
}
},
grid: {
left: 30,
right: 30,
bottom: 20,
top: 30,
containLabel: true
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
},
padding: [5, 10]
},
yAxis: {
axisTick: {
show: false
}
},
legend: {
data: [this.name1, this.name2]
},
series: [{
name: this.name1, itemStyle: {
normal: {
color: '#FF005A',
lineStyle: {
color: '#FF005A',
width: 2
}
}
},
smooth: true,
type: 'line',
data: this.expectedData,
animationDuration: 2800,
animationEasing: 'cubicInOut'
},
{
name: this.name2,
smooth: true,
type: 'line',
itemStyle: {
normal: {
color: '#3888fa',
lineStyle: {
color: '#3888fa',
width: 2
},
areaStyle: {
color: '#f3f8ff'
}
}
},
data: this.actualData,
animationDuration: 2800,
animationEasing: 'quadraticOut'
}]
})
}
}
}
</script>