上一片笔记封装了柱形图和折线图
这一篇封装饼图、仪表盘和状态图
首先是饼图:
<template> <div> <div ref='piechart' class='echartbox'> </div> </div> </template> <script> let echarts = require('echarts/lib/echarts') // 引入饼图组件 require('echarts/lib/chart/pie') // 引入提示框和title组件 require('echarts/lib/component/tooltip') require('echarts/lib/component/title') require('echarts/lib/component/legend') export default { name: 'Pie', props: { // texttitle: String, // legenddata: Array, // seriesdata: Array, textlink: { type: String, required: false, default: '' }, clicklink: { type: Boolean, required: false, default: false }, piedata: Object }, data () { return { link: this.textlink, click_link: this.clicklink, title: '', legend_data: [], series_data: [] } }, watch: { piedata (val) { this.title = val.title this.legend_data = val.legend_data this.series_data = val.series_data this.drawPie() } }, mounted () { // this.drawPie() }, methods: { drawPie () { let myCharts = echarts.init(this.$refs.piechart) myCharts.setOption({ color: ['#83d0d5', '#f1cb48', '#188ae2', '#E8830B', '#7460ae', '#fc4b6c', '#31ce77', '#eae0bc', '#e732cb', '#9dce8a'], title: { text: this.title, left: '35', top: '20', link: this.link, textStyle: { color: '#B6B6B6' } }, tooltip: { trigger: 'item', formatter: '{b} : {c} ({d}%)' }, legend: { bottom: 10, left: 'center', data: this.legend_data, textStyle: { color: '#B6B6B6' } }, series: [ { name: this.title, type: 'pie', radius: '55%', center: ['50%', '45%'], avoidLabelOverlap: false, data: this.series_data, label: { normal: { formatter: '{c}' } } } ] }) myCharts.on('click', this.clickEchats) }, clickEchats (param) { console.log(param) if (this.click_link) { this.click_link = 'https://www.baidu.com/' window.location.href = this.click_link } } } } </script>
注意点:
1.饼图没有axis轴的数据,座椅后台返回的参数通常是三个,title,legend_data,series,我们将其直接一起放在piedata传递给子组件,一起传除了父组件传参的时候看不来不冗余,还有一个重要的原因,我们只需要在子组件中监听piedata的变化即可,然后会重新绘制图表,要不然需要监听三个参数
2.其他传默认值和bar图是一样的,不浪费口舌了,饼图没做自适应,因为大小差不了多少
3.饼图添加了一个点击的功能,就是点击饼图的那一部分,会跳转,但是不是所有的饼图都会跳转,所以设置了一个布尔值,默认是false,不传值默认就是false,不能点击,如果传值的话,传true的话们就可以点击。
myCharts.on('click', this.clickEchats) }, clickEchats (param) { console.log(param) if (this.click_link) { this.click_link = 'https://www.baidu.com/' window.location.href = this.click_link } } }
给echarts添加点击事件,如果click的值为true的话,就会实现跳转。
文章来源: Vue封装一个饼图、仪表盘和状态图