之前记过vue中antV G2图表的使用https://www.jianshu.com/p/a836ae8aeeb7(折线)
现在为了减少代码量,简单封装一下,效果如下
image-20200909132848799.png
基本使用
子组件
新建LineChart.vue文件,里面是要封装的内容。
//id设成属性值方便多次使用,样式
父组件引用子组件
//这里:id绑定格式要绑字符串
★需求是Tabs页展示不同时段的数据统计结果
(明明用按钮更方便☺,用按钮的话只要一个图表,更新数据就可以了。更新数据相关https://blog.csdn.net/weixin_42275932/article/details/90080199?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.edu_weight&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.edu_weight
)
UI组件用的是antdv,将四个图表挂在四个tab-pane上,需要注意的是所有tab-pane页都要强行渲染,api用forceRender(被隐藏时是否渲染)
不渲染的话是空白的!!!不渲染的话是空白的!!!不渲染的话是空白的!!!
优化
目前是横坐标的字段是time,纵坐标的字段是count,默认有坐标轴,辅助线,和图例。
控制一下坐标轴辅助线和图例的显示,将高度也放在父组件里传入。
LineChart.vue的prop:
props: {
chartData: {
type: Array,
default: () => [],
},
id: {
type: String,
default: '',
},
height: { //高度
type: Number,
default: 300,
},
legend: { //图例
type: Boolean,
default:true,
},
axisX: { //横坐标
type: Boolean,
default:true,
},
axisY: { //纵坐标
type: Boolean,
default:true,
},
},
LineChart.vue的initLineChart:
initLineChart() {
this.chart && this.chart.destroy(); //如果存在就先删除
console.log('initLineChart success!!');
console.log(this.chartData)
this.chart = new Chart({
container: this.id,
autoFit: true,
height: this.height, // 控制高度
});
this.chart.data(this.chartData);
this.chart.scale({
time: {
range: [0, 1]
},
count: {
min: 0,
nice: true
},
});
this.chart.tooltip({
showCrosshairs: true, // 展示 Tooltip 辅助线
shared: true,
});
this.chart.axis('count',this.axisY); //控制横纵坐标,图例
this.chart.axis('time',this.axisX);
this.chart.legend(this.legend);
this.chart.line().position('time*count').color('type').shape('smooth');
this.chart.point().position('time*count').color('type').size(4).shape('circle').style({
stroke: '#fff',
lineWidth: 1
});
this.chart.render();
},
父组件的template:
这样就是高度100,不显示图例,也不显示横坐标、纵坐标。
其他想要控制的也可以这样。