本文实例为大家分享了VUE项目中封装Echart折线图的具体代码,供大家参考,具体内容如下
封装Echart折线图,可显示多条折线
1. 首先在项目中全局引入Echarts,main.js中:
import * as echarts from 'echarts' Vue.prototype.$echarts = echarts
2.components中新建组件baseLineChart.vue,以下代码直接复制:
<template> <div id="baseLineChart" ref="baseLineChart" :style="{ width: chartWidth, height: chartHeight }" /> </template> <script> export default { props: { chartData: { type: Array, default: () => [] }, timeX: { type: Array, default: () => [] }, chartName: { type: String, default: '' }, chartWidth: { type: String, default: '' }, chartHeight: { type: String, default: '' }, seriesName: { type: Array, default: () => [] }, chartUnit: { type: String, default: '' } }, data() { return { baseLineChart: null, newChartData: {} } }, computed: { chartOptions() { const options = { grid: { left: '4%', bottom: '8%', top: '15%', right: '0' }, tooltip: { trigger: 'axis' }, color: ['#1879BD', '#03B8DF', '#7B879A'], legend: { show: true, right: '0', top: '-1%', icon: 'circle' }, xAxis: [ { type: 'category', axisTick: { show: false }, data: [] } ], yAxis: [ { type: 'value', name: '', nameTextStyle: { padding: [0, 15, 0, 0] } } ], series: [] } return options } }, watch: { chartData: { handler(newValue, oldValue) { this.newChartData = newValue this.initData() }, deep: true } }, mounted() { this.$nextTick(() => { this.initChart() if (this.chartData) { this.initData() } }) }, methods: { initChart() { const _this = this _this.baseLineChart = _this.$echarts.init(this.$refs.baseLineChart) window.addEventListener('resize', function () { _this.baseLineChart.resize() }) }, initData() { let sData = [] if (this.chartData) { sData = this.chartData.map((val, index) => { return { data: val, name: this.seriesName[index], type: 'line' } }) this.chartOptions.series = sData } this.chartOptions.xAxis[0].data = this.timeX this.chartOptions.yAxis[0].name = `单位(${this.chartUnit})` this.baseLineChart.setOption(this.chartOptions, true) } } } </script>
配置项根据自身项目来定制。
3、在组件中引入:
<template> <div> <baseLine :chart-data="chartData" :time-x="timeX" chart-name="OEE" chart-width="1700px" chart-height="350px" :series-name="seriesName" chart-unit="%" /> </div> </template> import baseLine from '@/components/charts/baseLineChart.vue' <script> export default { components: { baseLine }, data() { return { timeX: [], chartData:[] seriesName: ['白班', '晚班'] } }, } </script>
chart-width 图表宽度
chart-height 图表高度
chart-unit 图表数据的显示单位
timeX为X轴数据,一般为时间数组 [‘1-1’,‘1-2’,‘1-3’ ];
chartData为折线数据,多条数据格式 [ [1,2,3],[4,5,6] ]
seriesName为每条折线对应名称
同理可封装其他图表
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持阿兔在线工具。