一、vue封装饼图、树状图、雷达图等组件
目录
resize.js需要utils.js
utils.js
import { parseTime } from './yunhis'/*** 表格时间格式化*/
export function formatDate(cellValue) {if (cellValue == null || cellValue == "") return "";var date = new Date(cellValue)var year = date.getFullYear()var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}/*** @param {number} time* @param {string} option* @returns {string}*/
export function formatTime(time, option) {if (('' + time).length === 10) {time = parseInt(time) * 1000} else {time = +time}const d = new Date(time)const now = Date.now()const diff = (now - d) / 1000if (diff < 30) {return '刚刚'} else if (diff < 3600) {// less 1 hourreturn Math.ceil(diff / 60) + '分钟前'} else if (diff < 3600 * 24) {return Math.ceil(diff / 3600) + '小时前'} else if (diff < 3600 * 24 * 2) {return '1天前'}if (option) {return parseTime(time, option)} else {return (d.getMonth() +1 +'月' +d.getDate() +'日' +d.getHours() +'时' +d.getMinutes() +'分')}
}/*** @param {string} url* @returns {Object}*/
export function getQueryObject(url) {url = url == null ? window.location.href : urlconst search = url.substring(url.lastIndexOf('?') + 1)const obj = {}const reg = /([^?&=]+)=([^?&=]*)/gsearch.replace(reg, (rs, $1, $2) => {const name = decodeURIComponent($1)let val = decodeURIComponent($2)val = String(val)obj[name] = valreturn rs})return obj
}/*** @param {string} input value* @returns {number} output value*/
export function byteLength(str) {// returns the byte length of an utf8 stringlet s = str.lengthfor (var i = str.length - 1; i >= 0; i--) {const code = str.charCodeAt(i)if (code > 0x7f && code <= 0x7ff) s++else if (code > 0x7ff && code <= 0xffff) s += 2if (code >= 0xDC00 && code <= 0xDFFF) i--}return s
}/*** @param {Array} actual* @returns {Array}*/
export function cleanArray(actual) {const newArray = []for (let i = 0; i < actual.length; i++) {if (actual[i]) {newArray.push(actual[i])}}return newArray
}/*** @param {Object} json* @returns {Array}*/
export function param(json) {if (!json) return ''return cleanArray(Object.keys(json).map(key => {if (json[key] === undefined) return ''return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])})).join('&')
}/*** @param {string} url* @returns {Object}*/
export function param2Obj(url) {const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')if (!search) {return {}}const obj = {}const searchArr = search.split('&')searchArr.forEach(v => {const index = v.indexOf('=')if (index !== -1) {const name = v.substring(0, index)const val = v.substring(index + 1, v.length)obj[name] = val}})return obj
}/*** @param {string} val* @returns {string}*/
export function html2Text(val) {const div = document.createElement('div')div.innerHTML = valreturn div.textContent || div.innerText
}/*** Merges two objects, giving the last one precedence* @param {Object} target* @param {(Object|Array)} source* @returns {Object}*/
export function objectMerge(target, source) {if (typeof target !== 'object') {target = {}}if (Array.isArray(source)) {return source.slice()}Object.keys(source).forEach(property => {const sourceProperty = source[property]if (typeof sourceProperty === 'object') {target[property] = objectMerge(target[property], sourceProperty)} else {target[property] = sourceProperty}})return target
}/*** @param {HTMLElement} element* @param {string} className*/
export function toggleClass(element, className) {if (!element || !className) {return}let classString = element.classNameconst nameIndex = classString.indexOf(className)if (nameIndex === -1) {classString += '' + className} else {classString =classString.substr(0, nameIndex) +classString.substr(nameIndex + className.length)}element.className = classString
}/*** @param {string} type* @returns {Date}*/
export function getTime(type) {if (type === 'start') {return new Date().getTime() - 3600 * 1000 * 24 * 90} else {return new Date(new Date().toDateString())}
}/*** @param {Function} func* @param {number} wait* @param {boolean} immediate* @return {*}*/
export function debounce(func, wait, immediate) {let timeout, args, context, timestamp, resultconst later = function() {// 据上一次触发时间间隔const last = +new Date() - timestamp// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 waitif (last < wait && last > 0) {timeout = setTimeout(later, wait - last)} else {timeout = null// 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用if (!immediate) {result = func.apply(context, args)if (!timeout) context = args = null}}}return function(...args) {context = thistimestamp = +new Date()const callNow = immediate && !timeout// 如果延时不存在,重新设定延时if (!timeout) timeout = setTimeout(later, wait)if (callNow) {result = func.apply(context, args)context = args = null}return result}
}/*** This is just a simple version of deep copy* Has a lot of edge cases bug* If you want to use a perfect deep copy, use lodash's _.cloneDeep* @param {Object} source* @returns {Object}*/
export function deepClone(source) {if (!source && typeof source !== 'object') {throw new Error('error arguments', 'deepClone')}const targetObj = source.constructor === Array ? [] : {}Object.keys(source).forEach(keys => {if (source[keys] && typeof source[keys] === 'object') {targetObj[keys] = deepClone(source[keys])} else {targetObj[keys] = source[keys]}})return targetObj
}/*** @param {Array} arr* @returns {Array}*/
export function uniqueArr(arr) {return Array.from(new Set(arr))
}/*** @returns {string}*/
export function createUniqueString() {const timestamp = +new Date() + ''const randomNum = parseInt((1 + Math.random()) * 65536) + ''return (+(randomNum + timestamp)).toString(32)
}/*** Check if an element has a class* @param {HTMLElement} elm* @param {string} cls* @returns {boolean}*/
export function hasClass(ele, cls) {return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}/*** Add class to element* @param {HTMLElement} elm* @param {string} cls*/
export function addClass(ele, cls) {if (!hasClass(ele, cls)) ele.className += ' ' + cls
}/*** Remove class from element* @param {HTMLElement} elm* @param {string} cls*/
export function removeClass(ele, cls) {if (hasClass(ele, cls)) {const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')ele.className = ele.className.replace(reg, ' ')}
}export function makeMap(str, expectsLowerCase) {const map = Object.create(null)const list = str.split(',')for (let i = 0; i < list.length; i++) {map[list[i]] = true}return expectsLowerCase? val => map[val.toLowerCase()]: val => map[val]
}export const exportDefault = 'export default 'export const beautifierConf = {html: {indent_size: '2',indent_char: ' ',max_preserve_newlines: '-1',preserve_newlines: false,keep_array_indentation: false,break_chained_methods: false,indent_scripts: 'separate',brace_style: 'end-expand',space_before_conditional: true,unescape_strings: false,jslint_happy: false,end_with_newline: true,wrap_line_length: '110',indent_inner_html: true,comma_first: false,e4x: true,indent_empty_lines: true},js: {indent_size: '2',indent_char: ' ',max_preserve_newlines: '-1',preserve_newlines: false,keep_array_indentation: false,break_chained_methods: false,indent_scripts: 'normal',brace_style: 'end-expand',space_before_conditional: true,unescape_strings: false,jslint_happy: true,end_with_newline: true,wrap_line_length: '110',indent_inner_html: true,comma_first: false,e4x: true,indent_empty_lines: true}
}// 首字母大小
export function titleCase(str) {return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}// 下划转驼峰
export function camelCase(str) {return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}export function isNumberStr(str) {return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}resize.js```js
import { debounce } from '@/utils'export default {data() {return {$_sidebarElm: null,$_resizeHandler: null}},mounted() {this.initListener()},activated() {if (!this.$_resizeHandler) {// avoid duplication initthis.initListener()}// when keep-alive chart activated, auto resizethis.resize()},beforeDestroy() {this.destroyListener()},deactivated() {this.destroyListener()},methods: {// use $_ for mixins properties// https://vuejs.org/v2/style-guide/index.html#Private-property-names-essential$_sidebarResizeHandler(e) {if (e.propertyName === 'width') {this.$_resizeHandler()}},initListener() {this.$_resizeHandler = debounce(() => {this.resize()}, 100)window.addEventListener('resize', this.$_resizeHandler)this.$_sidebarElm = document.getElementsByClassName('sidebar-container')[0]this.$_sidebarElm && this.$_sidebarElm.addEventListener('transitionend', this.$_sidebarResizeHandler)},destroyListener() {window.removeEventListener('resize', this.$_resizeHandler)this.$_resizeHandler = nullthis.$_sidebarElm && this.$_sidebarElm.removeEventListener('transitionend', this.$_sidebarResizeHandler)},resize() {const { chart } = thischart && chart.resize()}}
}
图形组件
BarChart.vue
<template><div :class="className" :style="{height:height,width:width}"/>
</template><script>
import * as echarts from 'echarts';require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'const animationDuration = 1000export default {mixins: [resize],props: {className: {type: String,default: 'chart'},width: {type: String,default: '100%'},height: {type: String,default: '400px'},chartData: {type: Object,required: true}},data() {return {chart: null}},mounted() {this.$nextTick(() => {this.initChart()})},beforeDestroy() {if (!this.chart) {return}this.chart.dispose()this.chart = null},watch: {chartData: {deep: true,handler(val) {this.setOptions(val)}}},methods: {initChart() {this.chart = echarts.init(this.$el, 'macarons')this.setOptions(this.chartData)},setOptions({xAxisData, listData, title} = {}) {let series = [];const legendData = [];for (var i in listData) {let seriesItem = {}// 名称seriesItem.name = listData[i].namelegendData.push(listData[i].name)// 柱状图seriesItem.type = 'bar'// 数据堆叠,同个类目轴上系列配置相同的stack值可以堆叠放置seriesItem.stack = listData[i].stack// 柱条的宽度,不设时自适应if (listData[i].barWidth && listData[i].barWidth > 0) {seriesItem.barWidth = listData[i].barWidth}// 数据内容数组。数组项通常为具体的数据项。顺序长度与xAxisData一致seriesItem.data = listData[i].data// 初始动画的时长if (listData[i].animationDuration && listData[i].animationDuration > 0) {seriesItem.animationDuration = listData[i].animationDuration} else {seriesItem.animationDuration = animationDuration}series.push(seriesItem);}this.chart.setOption({title: {show: true,text: title || '柱状图',left:"center"},legend: {data: legendData,bottom:3},toolbox: {feature: {magicType: {type: ['line', 'bar','stack', 'tiled']},dataView: {},restore: {},saveAsImage: {}}},tooltip: {trigger: 'axis',axisPointer: { // 坐标轴指示器,坐标轴触发有效type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'}},grid: {top: 30,left: '2%',right: '2%',bottom: '8%',containLabel: true},xAxis: [{type: 'category',data: xAxisData,axisTick: {alignWithLabel: true},}],yAxis: [{type: 'value',axisTick: {show: false}}],series: series})}}
}
</script>
LineCharts.vue
<template><div :class="className" :style="{height:height,width:width}"/>
</template><script>
import * as echarts from 'echarts';require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'export default {mixins: [resize],props: {className: {type: String,default: 'chart'},width: {type: String,default: '100%'},height: {type: String,default: '350px'},autoResize: {type: Boolean,default: true},chartData: {type: Object,required: true}},data() {return {chart: null}},watch: {chartData: {deep: true,handler(val) {this.setOptions(val)}}},mounted() {this.$nextTick(() => {this.initChart()})},beforeDestroy() {if (!this.chart) {return}this.chart.dispose()this.chart = null},methods: {initChart() {this.chart = echarts.init(this.$el, 'macarons')this.setOptions(this.chartData)},setOptions({title, xAxisData, listData} = {}) {const legendData= []const series=[]for (var i in listData) {legendData.push(listData[i].name)let seriesItem = {}// 折线名seriesItem.name = listData[i].name// 是否平滑曲线显示seriesItem.smooth = listData[i].smooth || true// 折线seriesItem.type = 'line',// 数据内容,通常是数组,顺序长度与xAxisData一致seriesItem.data = listData[i].data// 初始动画的时长if (listData[i].animationDuration && listData[i].animationDuration > 0) {seriesItem.animationDuration = listData[i].animationDuration} else {seriesItem.animationDuration = 2800}// 初始动画的缓动效果 linear quadraticIn quadraticOut cubicIn cubicOut sinusoidalOutseriesItem.animationEasing = listData[i].animationEasingseries.push(seriesItem);}this.chart.setOption({title: {show: true,text: title || '折线图',left:'center'},toolbox: {feature: {magicType: {type: ['line', 'bar','tiled']},dataView: {},restore: {},saveAsImage: {}}},// 直角坐标系 grid 中的 x 轴,一般情况下单个 grid 组件最多只能放上下两个 x 轴,多于两个 x 轴需要通过配置 offset 属性防止同个位置多个 x 轴的重叠。xAxis: {/*** 类目数据,在类目轴(type: 'category')中有效。* 如果没有设置 type,但是设置了 axis.data,则认为 type 是 'category'。* 如果设置了 type 是 'category',但没有设置 axis.data,则 axis.data 的内容会自动从 series.data 中获取,这会比较方便。不过注意,axis.data 指明的是 'category' 轴的取值范围。如果不指定而是从 series.data 中获取,那么只能获取到 series.data 中出现的值。比如说,假如 series.data 为空时,就什么也获取不到。** 示例:* // 所有类目名称列表* data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']* // 每一项也可以是具体的配置项,此时取配置项中的 `value` 为类目名* data: [{* value: '周一',* // 突出周一* textStyle: {* fontSize: 20,* color: 'red'* }* }, '周二', '周三', '周四', '周五', '周六', '周日']*/type:'category',data: xAxisData,/*** 坐标轴两边留白策略,类目轴和非类目轴的设置和表现不一样。* 类目轴中 boundaryGap 可以配置为 true 和 false。默认为 true,这时候刻度只是作为分隔线,标签和数据点都会在两个刻度之间的带(band)中间。* 非类目轴,包括时间,数值,对数轴,boundaryGap是一个两个值的数组,分别表示数据最小值和最大值的延伸范围,可以直接设置数值或者相对的百分比,在设置 min 和 max 后无效。 示例:* boundaryGap: ['20%', '20%']*/boundaryGap: false,// 坐标轴刻度相关设置。axisTick: {//是否显示坐标轴刻度。show: false}},/*** 直角坐标系内绘图网格,单个 grid 内最多可以放置上下两个 X 轴,左右两个 Y 轴。可以在网格上绘制折线图,柱状图,散点图(气泡图)。** 在 ECharts 2.x 里单个 echarts 实例中最多只能存在一个 grid 组件,在 ECharts 3 中可以存在任意个 grid 组件。*/grid: {/*** grid 组件离容器左侧的距离。** left 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,也可以是 'left', 'center', 'right'。** 如果 left 的值为'left', 'center', 'right',组件会根据相应的位置自动对齐。*/left: 10,// grid 组件离容器右侧的距离。right: 10,// grid 组件离容器下侧的距离。bottom: 20,// grid 组件离容器上侧的距离top: 30,/*** grid 区域是否包含坐标轴的刻度标签。** containLabel 为 false 的时候:* grid.left grid.right grid.top grid.bottom grid.width grid.height 决定的是由坐标轴形成的矩形的尺寸和位置。* 这比较适用于多个 grid 进行对齐的场景,因为往往多个 grid 对齐的时候,是依据坐标轴来对齐的。* containLabel 为 true 的时候:* grid.left grid.right grid.top grid.bottom grid.width grid.height 决定的是包括了坐标轴标签在内的所有内容所形成的矩形的位置。* 这常用于『防止标签溢出』的场景,标签溢出指的是,标签长度动态变化时,可能会溢出容器或者覆盖其他组件。*/containLabel: true},tooltip: {trigger: 'axis',axisPointer: {type: 'cross'},padding: [5, 10]},// 直角坐标系 grid 中的 y 轴,一般情况下单个 grid 组件最多只能放左右两个 y 轴,多于两个 y 轴需要通过配置 offset 属性防止同个位置多个 Y 轴的重叠。yAxis: {// 坐标轴刻度相关设置。axisTick: {show: false}},legend: {left:10,data: legendData},series: series})}}
}
</script>
PanelCharts.vue
<template><el-row :gutter="40" class="panel-group"><el-col :xs="12" :sm="12" :lg="6" class="card-panel-col"><div class="card-panel" @click="handleSetLineChartData('newVisitis')"><div class="card-panel-icon-wrapper icon-people"><svg-icon icon-class="peoples" class-name="card-panel-icon" /></div><div class="card-panel-description"><div class="card-panel-text">访客</div><count-to :start-val="0" :end-val="102400" :duration="2600" class="card-panel-num" /></div></div></el-col><el-col :xs="12" :sm="12" :lg="6" class="card-panel-col"><div class="card-panel" @click="handleSetLineChartData('messages')"><div class="card-panel-icon-wrapper icon-message"><svg-icon icon-class="message" class-name="card-panel-icon" /></div><div class="card-panel-description"><div class="card-panel-text">消息</div><count-to :start-val="0" :end-val="81212" :duration="3000" class="card-panel-num" /></div></div></el-col><el-col :xs="12" :sm="12" :lg="6" class="card-panel-col"><div class="card-panel" @click="handleSetLineChartData('purchases')"><div class="card-panel-icon-wrapper icon-money"><svg-icon icon-class="money" class-name="card-panel-icon" /></div><div class="card-panel-description"><div class="card-panel-text">金额</div><count-to :start-val="0" :end-val="9280" :duration="3200" class="card-panel-num" /></div></div></el-col><el-col :xs="12" :sm="12" :lg="6" class="card-panel-col"><div class="card-panel" @click="handleSetLineChartData('shoppings')"><div class="card-panel-icon-wrapper icon-shopping"><svg-icon icon-class="shopping" class-name="card-panel-icon" /></div><div class="card-panel-description"><div class="card-panel-text">订单</div><count-to :start-val="0" :end-val="13600" :duration="3600" class="card-panel-num" /></div></div></el-col></el-row>
</template><script>
import CountTo from 'vue-count-to'export default {components: {CountTo},methods: {handleSetLineChartData(type) {this.$emit('handleSetLineChartData', type)}}
}
</script><style lang="scss" scoped>
.panel-group {margin-top: 18px;.card-panel-col {margin-bottom: 32px;}.card-panel {height: 108px;cursor: pointer;font-size: 12px;position: relative;overflow: hidden;color: #666;background: #fff;box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);border-color: rgba(0, 0, 0, .05);&:hover {.card-panel-icon-wrapper {color: #fff;}.icon-people {background: #40c9c6;}.icon-message {background: #36a3f7;}.icon-money {background: #f4516c;}.icon-shopping {background: #34bfa3}}.icon-people {color: #40c9c6;}.icon-message {color: #36a3f7;}.icon-money {color: #f4516c;}.icon-shopping {color: #34bfa3}.card-panel-icon-wrapper {float: left;margin: 14px 0 0 14px;padding: 16px;transition: all 0.38s ease-out;border-radius: 6px;}.card-panel-icon {float: left;font-size: 48px;}.card-panel-description {float: right;font-weight: bold;margin: 26px;margin-left: 0px;.card-panel-text {line-height: 18px;color: rgba(0, 0, 0, 0.45);font-size: 16px;margin-bottom: 12px;}.card-panel-num {font-size: 20px;}}}
}@media (max-width:550px) {.card-panel-description {display: none;}.card-panel-icon-wrapper {float: none !important;width: 100%;height: 100%;margin: 0 !important;.svg-icon {display: block;margin: 14px auto !important;float: none !important;}}
}
</style>
PieCharts.vue
<template><div :class="className" :style="{height:height,width:width}" />
</template><script>
import * as echarts from 'echarts';
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'export default {mixins: [resize],props: {className: {type: String,default: 'chart'},width: {type: String,default: '100%'},height: {type: String,default: '400px'},chartData: {type: Object,required: true}},data() {return {chart: null}},mounted() {this.$nextTick(() => {this.initChart()})},beforeDestroy() {if (!this.chart) {return}this.chart.dispose()this.chart = null},watch: {chartData: {deep: true,handler(val) {this.setOptions(val)}}},methods: {initChart() {this.chart = echarts.init(this.$el, 'macarons')this.setOptions(this.chartData)},setOptions({ legendData,listData,title } = {}){let series = [];for(var i in listData){let seriesItem = {}// 系列名称seriesItem.name= listData[i].name || 'WEEKLY WRITE ARTICLES'// 饼图seriesItem.type= 'pie'// 是否展示成南丁格尔图,通过半径区分数据大小。可选择两种模式:// 'radius' 扇区圆心角展现数据的百分比,半径展现数据的大小。// 'area' 所有扇区圆心角相同,仅通过半径展现数据大小。seriesItem.roseType= listData[i].roseType || 'radius'/*饼图的半径。可以为如下类型:number:直接指定外半径值。string:例如,'20%',表示外半径为可视区尺寸(容器高宽中较小一项)的 20% 长度。Array.<number|string>:数组的第一项是内半径,第二项是外半径。每一项遵从上述 number string 的描述。可以将内半径设大显示成圆环图(Donut chart)。*/seriesItem.radius= listData[i].radius || [15, 95]/*饼图的中心(圆心)坐标,数组的第一项是横坐标,第二项是纵坐标。支持设置成百分比,设置成百分比时第一项是相对于容器宽度,第二项是相对于容器高度。*/seriesItem.center= listData[i].center || ['50%', '38%']/*** 系列中的数据内容数组。数组项可以为单个数值,如:* [12, 34, 56, 10, 23]** 如果需要在数据中加入其它维度给 visualMap 组件用来映射到颜色等其它图形属性。每个数据项也可以是数组,如:* [[12, 14], [34, 50], [56, 30], [10, 15], [23, 10]]* 这时候可以将每项数组中的第二个值指定给 visualMap 组件。** 更多时候我们需要指定每个数据项的名称,这时候需要每个项为一个对象:* [{* // 数据项的名称* name: '数据1',* // 数据项值8* value: 10* }, {* name: '数据2',* value: 20* }]** 需要对个别内容指定进行个性化定义时:* [{* name: '数据1',* value: 10* }, {* // 数据项名称* name: '数据2',* value : 56,* //自定义特殊 tooltip,仅对该数据项有效* tooltip:{},* //自定义特殊itemStyle,仅对该item有效* itemStyle:{}* }]*/seriesItem.data= listData[i].data || [{ value: 320, name: 'Industries' },{ value: 240, name: 'Technology' },{ value: 149, name: 'Forex' },{ value: 100, name: 'Gold' },{ value: 59, name: 'Forecasts' }],// 初始动画的缓动效果seriesItem.animationEasing=listData[i].animationEasing||'cubicInOut'/*** 初始动画的时长,支持回调函数,可以通过每个数据返回不同的时长实现更戏剧的初始动画效果:** animationDuration: function (idx) {* // 越往后的数据时长越大* return idx * 100;* }*/seriesItem.animationDuration= listData[i].animationDuration || 2600series.push(seriesItem)}this.chart.setOption({title: {show: true,text: title || '饼状图',top:"-5",left:"center",},toolbox: {feature: {dataView: {},restore: {},saveAsImage: {}},},// 提示框组件tooltip: {/*** 触发类型。* 可选:* 'item' 数据项图形触发,主要在散点图,饼图等无类目轴的图表中使用。** 'axis'坐标轴触发,主要在柱状图,折线图等会使用类目轴的图表中使用。* 在 ECharts 2.x 中只支持类目轴上使用 axis trigger,在 ECharts 3 中支持在直角坐标系和极坐标系上的所有类型的轴。并且可以通过 axisPointer.axis 指定坐标轴。** 'none'什么都不触发。*/trigger: 'item',/*** 提示框浮层内容格式器,支持字符串模板和回调函数两种形式*/formatter: '{a} <br/>{b} : {c} ({d}%)'},// 图例组件。 图例组件展现了不同系列的标记(symbol),颜色和名字。可以通过点击图例控制哪些系列不显legend: {// 图例组件离容器左侧的距离。left: 'center',// 图例组件离容器下侧的距离。bottom: '5',// data: ['Industries', 'Technology', 'Forex', 'Gold', 'Forecasts']/*** 图例的数据数组。数组项通常为一个字符串,每一项代表一个系列的 name(如果是饼图,也可以是饼图单个数据的 name)。图例组件会自动根据对应系列的图形标记(symbol)来绘制自己的颜色和标记,特殊字符串 ''(空字符串)或者 '\n'(换行字符串)用于图例的换行。** 如果 data 没有被指定,会自动从当前系列中获取。多数系列会取自 series.name 或者 series.encode 的 seriesName 所指定的维度。如 饼图 and 漏斗图 等会取自 series.data 中的 name。** 如果要设置单独一项的样式,也可以把该项写成配置项对象。此时必须使用 name 属性对应表示系列的 name。*/data:legendData},// 系列列表。每个系列通过 type 决定自己的图表类型series: series})}}
}
</script>
RaddarCharts.vue
<template><div :class="className" :style="{height:height,width:width}" />
</template><script>
import * as echarts from 'echarts';
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'const animationDuration = 3000export default {mixins: [resize],props: {className: {type: String,default: 'chart'},width: {type: String,default: '100%'},height: {type: String,default: '300px'},chartData: {type: Object,required: true}},data() {return {chart: null}},mounted() {this.$nextTick(() => {this.initChart()})},beforeDestroy() {if (!this.chart) {return}this.chart.dispose()this.chart = null},watch: {chartData: {deep: true,handler(val) {this.setOptions(val)}}},methods: {initChart() {this.chart = echarts.init(this.$el, 'macarons')this.setOptions(this.chartData)},setOptions({ indicatorData,listData,title } = {}){const legendData = [];for(var i in listData){legendData.push(listData[i].name)}this.chart.setOption({title: {show: true,text: title || '雷达图'},toolbox: {feature: {dataView: {},restore: {},saveAsImage: {}}},// 提示框组件tooltip: {/*** 触发类型。* 可选:* 'item' 数据项图形触发,主要在散点图,饼图等无类目轴的图表中使用。** 'axis'坐标轴触发,主要在柱状图,折线图等会使用类目轴的图表中使用。* 在 ECharts 2.x 中只支持类目轴上使用 axis trigger,在 ECharts 3 中支持在直角坐标系和极坐标系上的所有类型的轴。并且可以通过 axisPointer.axis 指定坐标轴。** 'none'什么都不触发。*/trigger: 'axis',axisPointer: { // 坐标轴指示器,坐标轴触发有效type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'}},// 雷达图坐标系组件,只适用于雷达图。该组件等同 ECharts 2 中的 polar 组件radar: {/*** 半径。可以为如下类型:** number:直接指定外半径值。* string:例如,'20%',表示外半径为可视区尺寸(容器高宽中较小一项)的 20% 长度。* Array.<number|string>:数组的第一项是内半径,第二项是外半径。每一项遵从上述 number string 的描述。*/radius: '66%',/*** 中心(圆心)坐标,数组的第一项是横坐标,第二项是纵坐标。* 支持设置成百分比,设置成百分比时第一项是相对于容器宽度,第二项是相对于容器高度。** 使用示例:* // 设置成绝对的像素值* center: [400, 300]* // 设置成相对的百分比* center: ['50%', '50%']*/center: ['50%', '42%'],// 指示器轴的分割段数。splitNumber: 8,// 坐标轴在 grid 区域中的分隔区域,默认不显示splitArea: {// 分隔区域的样式设置。areaStyle: {// 分隔区域颜色。分隔区域会按数组中颜色的顺序依次循环设置颜色。默认是一个深浅的间隔色。color: 'rgba(127,95,132,.3)',// 图形透明度。支持从 0 到 1 的数字,为 0 时不绘制该图形。opacity: 1,/*** 图形阴影的模糊大小。该属性配合 shadowColor,shadowOffsetX, shadowOffsetY 一起设置图形的阴影效果。* 示例:* {* shadowColor: 'rgba(0, 0, 0, 0.5)',* shadowBlur: 10* }*/shadowBlur: 45,shadowColor: 'rgba(0,0,0,.5)',// 阴影水平方向上的偏移距离。shadowOffsetX: 0,// 阴影垂直方向上的偏移距离。shadowOffsetY: 15}},/*** 雷达图的指示器,用来指定雷达图中的多个变量(维度),如下示例。** indicator: [* { name: '销售(sales)', max: 6500},* { name: '管理(Administration)', max: 16000, color: 'red'}, // 标签设置为红色* { name: '信息技术(Information Techology)', max: 30000},* { name: '客服(Customer Support)', max: 38000},* { name: '研发(Development)', max: 52000},* { name: '市场(Marketing)', max: 25000}* ]*/indicator: indicatorData// indicator: [// { name: 'Sales', max: 10000 },// { name: 'Administration', max: 20000 },// { name: 'Information Techology', max: 20000 },// { name: 'Customer Support', max: 20000 },// { name: 'Development', max: 20000 },// { name: 'Marketing', max: 20000 }// ]},// 图例组件。legend: {/*** 图例组件离容器左侧的距离。** left 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,也可以是 'left', 'center', 'right'。** 如果 left 的值为 'left', 'center', 'right',组件会根据相应的位置自动对齐。*/left: 'center',/*** 图例组件离容器下侧的距离。** bottom 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。** 默认自适应。*/bottom: '10',// data: ['Allocated Budget', 'Expected Spending', 'Actual Spending']/*** 图例的数据数组。数组项通常为一个字符串,每一项代表一个系列的 name(如果是饼图,也可以是饼图单个数据的 name)*/data:legendData},series: [{// 雷达图type: 'radar',/*** 标记的大小,可以设置成诸如 10 这样单一的数字,也可以用数组分开表示宽和高,例如 [20, 10] 表示标记宽为20,高为10。** 如果需要每个数据的图形大小不一样,可以设置为如下格式的回调函数:** (value: Array|number, params: Object) => number|Array* 其中第一个参数 value 为 data 中的数据值。第二个参数params 是其它的数据项参数。*/symbolSize: 0,/*** 区域填充样式。*/areaStyle: {normal: {/*** 图形阴影的模糊大小。该属性配合 shadowColor,shadowOffsetX, shadowOffsetY 一起设置图形的阴影效果。* 示例:* {* shadowColor: 'rgba(0, 0, 0, 0.5)',* shadowBlur: 10* }*/shadowBlur: 13,shadowColor: 'rgba(0,0,0,.2)',// 阴影水平方向上的偏移距离。shadowOffsetX: 0,// 阴影垂直方向上的偏移距离。shadowOffsetY: 10,// 图形透明度。支持从 0 到 1 的数字,为 0 时不绘制该图形opacity: 1}},/*** 雷达图的数据是多变量(维度)的,如下示例:** data : [* {* value : [4300, 10000, 28000, 35000, 50000, 19000],* name : '预算分配(Allocated Budget)'* },* {* value : [5000, 14000, 28000, 31000, 42000, 21000],* name : '实际开销(Actual Spending)'* }* ]* 其中的value项数组是具体的数据,每个值跟 radar.indicator 一一对应。*/data: listData,// data: [// {// value: [5000, 7000, 12000, 11000, 15000, 14000],// name: 'Allocated Budget'// },// {// value: [4000, 9000, 15000, 15000, 13000, 11000],// name: 'Expected Spending'// },// {// value: [5500, 11000, 12000, 15000, 12000, 12000],// name: 'Actual Spending'// }// ],/*** 初始动画的时长,支持回调函数,可以通过每个数据返回不同的时长实现更戏剧的初始动画效果:** animationDuration: function (idx) {* // 越往后的数据时长越大* return idx * 100;* }*/animationDuration: animationDuration}]})}}
}
</script>
二、饼图
步骤:导入组件,传入数据
点击表格某一行,弹出点击行的饼图。效果图如下
vue代码
<template><div class="app-container"><ta-card title="条件搜索" :bordered="false" :showExpand="false" style="margin-bottom: 18px;"><el-form :model="queryParams"ref="queryform"size="small"@submit.native.prevent:inline="true"label-width="80px"><el-form-item label="查询时间" prop="dateScope"><el-date-pickervalue-format="yyyy-MM-dd HH:mm:ss"v-model="queryParams.dateScope"type="datetimerange"start-placeholder="开始日期"end-placeholder="结束日期":default-time="['12:00:00']"></el-date-picker></el-form-item><el-form-item label="医生" prop="ysbms" width="70px"><el-select v-model="queryParams.ysbms" multiple clearable placeholder="请选择医生" filterable ><el-optionv-for="item in dict.type.SYS_USER":key="item.value":label="item.label":value="item.value"></el-option></el-select></el-form-item><el-form-item label="费用类型" prop="fylbs" width="70px"><el-select v-model="queryParams.fylbs" multiple clearable placeholder="请选择费用类别" filterable ><el-optionv-for="item in dict.type.FYLB":key="item.value":label="item.label":value="item.value"></el-option></el-select></el-form-item><el-form-item :style="isCollapse?'position: absolute;right: 4.8%;':'position: absolute;right: 1.1%;'"><el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button><el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button></el-form-item></el-form></ta-card><ta-card title="门诊收费统计-医生统计" :bordered="false" :showExpand="false"><el-table :data="tableData"highlight-current-row@current-change="tableRowClassName" stripe><el-table-columnv-for="(item, index) in tableHeader":key="index":prop="item.val":label="item.name"></el-table-column></el-table><pagination:total="total":page.sync="queryParams.pageNum":limit.sync="queryParams.pageSize"@pagination="getList"/></ta-card><el-dialog title="门诊医生收费饼图" :visible.sync="pieOpen" width="1400px" append-to-body @close="pieOpenClose" ><pie-chart :chart-data="pieChartData"/></el-dialog></div>
</template><style lang="less">
.el-table .exit-row{background: #f6f68b;
}
.el-table .success-row{background: #d4f6c1;
}
</style><script>
import { listMzsfByYsbm,listMzsfFylbByYsbm } from '@/api/analysis/mz/mzsf'
import PieChart from '../dashboard/PieChart.vue'
export default {name: 'ysbm',dicts: ['SYS_USER','FYLB'],components: {PieChart},data () {return {// 总条数total: 0,//表格数据加载状态loading: false,queryParams: {pageNum: 1,pageSize: 10,dateScope:null,startDate:null,endDate:null,ysbms:null,fylbs:null,},tableData: [], // 获取到的表格数据tableHeader: [], // 表头数据//饼状图//弹出层pieOpen:false,//饼图数据pieChartData:{},}},created() {this.getList();},methods:{/** 搜索按钮操作 */handleQuery() {this.queryParams.pageNum = 1;this.getList();},/** 重置按钮操作 */resetQuery() {this.resetForm("queryform");this.queryParams.yTjpzh=null;this.handleQuery();},//初始化查询getList(){this.loading=true;if(this.queryParams.dateScope==null || this.queryParams.dateScope==""){this.queryParams.startDate=null;this.queryParams.endDate=null;}else{this.queryParams.startDate=this.queryParams.dateScope[0];this.queryParams.endDate=this.queryParams.dateScope[1];}//查询表格数据listMzsfByYsbm(this.queryParams).then(response => {this.tableData = response.rows;this.total = response.total;});//获取表头设置表头的name(key)-val(表头名字)listMzsfFylbByYsbm(this.queryParams).then(response => {//每次刷新表头为空this.tableHeader=[];let headNameArr=response.data.name; //表头名let headValArr=response.data.val; //表头对应的字段名,也就是Java实体类对应的属性// 转化表头数据headNameArr.forEach((item, index) => {this.tableHeader.push({val: headValArr[index], // 表头对应的表头名name: item // 表中要显示的数据})})});this.loading = false;},/** 导出按钮操作 */handleExport() {this.download('/mz/mzrctjbb/byysbm/export', {...this.queryParams}, `yptj_${new Date().getTime()}.xlsx`)},/**表格某一行双击事件*/tableRowClassName(val) {this.pieOpen=true;//获取点击行的数据let tmp=[];for(var i=0;i<this.tableData.length;i++){if(this.tableData[i].ysxm==val.ysxm){tmp=this.tableData[i];break;}};let l = [];let d = [];//求不是空的数据方便生成饼图let filteredData = {};for (let key in tmp) {if (tmp.hasOwnProperty(key)) {let value = tmp[key];if (value !== 0 && value !== null) {filteredData[key] = value;}}};//数据转换为饼图for (let key in filteredData) {if (tmp.hasOwnProperty(key)) {let value = tmp[key];for (let i = 0; i < this.tableHeader.length; i++) {if(key==this.tableHeader[i].val && key!="ysxm" && key != "sumRow"){l[i]=this.tableHeader[i].name;var t={value:value,name:this.tableHeader[i].name};d[i]=t;}}}};//饼图数据this.pieChartData={title:val.ysxm+"门诊项目收费饼图",legendData: l,listData: [{data:d,}]}},//饼图/** 饼图展示退出详情 */pieOpenClose(){this.pieOpen = false;this.pieChartData={};},}
}</script>
二、树状图
步骤:导入组件,传入数据
点击表格某一行,弹出点击行的树状图。效果图如下
vue代码
<template><div class="app-container"><ta-card title="条件搜索" :bordered="false" :showExpand="false" style="margin-bottom: 18px;"><el-form :model="queryParams"ref="queryform"size="small"@submit.native.prevent:inline="true"label-width="70px"><el-form-item label="查询时间" prop="dateScope"><el-date-pickervalue-format="yyyy-MM-dd HH:mm:ss"v-model="queryParams.dateScope"type="datetimerange"start-placeholder="开始日期"end-placeholder="结束日期":default-time="['12:00:00']"></el-date-picker></el-form-item><el-form-item ><el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button><el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button></el-form-item></el-form></ta-card><ta-card title="项目类型列表" :bordered="false" :showExpand="false"><template slot="extra" style="text-align: right;"><el-col :span="1.5"><el-buttontype="warning"plainicon="el-icon-download"size="mini"@click="handleExport"v-hasPermi="['yf:yptj:export']">下载</el-button></el-col></template><el-table v-loading="loading":data="tableData"style="width: 100%"height="410px"highlight-current-row@current-change="tableRowClassName" ><!--表格数据为空展示--><div slot="empty"><img src="@/assets/images/icon-no-content.png"></div><el-table-column label="项目名称" align="center" prop="fymc" /><el-table-column label="收费金额" align="center" prop="fyje" /><el-table-column label="单据张数" align="center" prop="djzs" /><el-table-column label="每张平均金额" align="center" prop="pjdjje" /><el-table-column label="项目比例%" align="center" prop="lbbi" /></el-table><pagination:total="total":page.sync="queryParams.pageNum":limit.sync="queryParams.pageSize"@pagination="getList"/></ta-card><el-dialog title="门诊项目收费" :visible.sync="barOpen" width="1400px" append-to-body @close="barOpenClose" ><bar-chart :chart-data="barChartData"/></el-dialog></div>
</template><style lang="less">
.el-table .exit-row{background: #f6f68b;
}
.el-table .success-row{background: #d4f6c1;
}
</style><script>
import { listMzLbSfVoByfylb } from '@/api/analysis/mz/mzsf'
import BarChart from '../dashboard/BarChart.vue'
export default {name: 'yfcf',dicts: ['FYLB'],components: {BarChart},data () {return {// 总条数total: 0,//表格数据加载状态loading: false,queryParams: {pageNum: 1,pageSize: 10,dateScope:null,startDate:null,endDate:null,},tableData: [], // 获取到的表格数据//柱状图//弹出层barOpen:false,//柱状图数据barChartData:{},}},created() {this.getList();},methods:{/** 搜索按钮操作 */handleQuery() {this.queryParams.pageNum = 1;this.getList();},/** 重置按钮操作 */resetQuery() {this.resetForm("queryform");this.queryParams.yTjpzh=null;this.handleQuery();},//初始化查询getList(){this.loading=true;if(this.queryParams.dateScope==null || this.queryParams.dateScope==""){this.queryParams.startDate=null;this.queryParams.endDate=null;}else{this.queryParams.startDate=this.queryParams.dateScope[0];this.queryParams.endDate=this.queryParams.dateScope[1];}listMzLbSfVoByfylb(this.queryParams).then(response => {this.tableData = response.rows;this.total = response.total;this.loading = false;});this.loading = false;},/** 导出按钮操作 */handleExport() {this.download('/mz/mzfy/byfylb/export', {...this.queryParams}, `yptj_${new Date().getTime()}.xlsx`)},/**表格某一行双击事件*/tableRowClassName(val) {this.barOpen=true;//横坐标let x = [];//图例let l1 = [];let l2 = [];let l3 = [];//数据转换为饼图for (let i = 0; i < this.tableData.length; i++) {x[i]=this.tableData[i].fymc;//费用金额l1[i]=this.tableData[i].fyje;//单据数l2[i]=this.tableData[i].djzs;//每张单据平均l3[i]=this.tableData[i].pjdjje;};//柱状图数据this.barChartData={title:"门诊项目收费",xAxisData: x,listData:[{name:"费用金额",data:l1},{name:"单据数",data:l2},{name:"每张平均金额",data:l3},]}},/** 柱状图图展示退出详情 */barOpenClose(){this.barOpen = false;this.barChartData={};},}
}</script>