在vue中使用echarts实现动态数据展示,以及echarts图表自适应
在vue中使用echarts实现动态数据展示
·
在平常的项目中,echarts图表我们也是使用的非常多的,通常我们从后端拿到数据,需要在图表上动态的进行呈现,接下来我们就模拟从后端获取数据然后进行呈现的方法
首先我们通过以下这条命令来安装echarts依赖
npm install echarts --save
然后在需要用到echarts的页面中进行引入
import echarts from "echarts";
需要实现的页面
点击对应的按钮,切换对应的数据
具体代码如下
<template>
<div>
<el-button :type="dianliuS" size="mini" @click="clickDL">电流</el-button>
<el-button :type="dianyaS" size="mini" @click="clickDY">电压</el-button>
<el-button :type="sanxiangS" size="mini" @click="clickSx"
>三项电流</el-button
>
<div id="main" style="width: 100%; height: 500px"></div>
</div>
</template>
<script>
import * as echarts from 'echarts'
export default {
data() {
return {
title: '',
dianliuS: '',
dianyaS: '',
sanxiangS: '',
series: '', //echarts数据对象
xAxis: [
'00:00',
'02:00',
'04:00',
'06:00',
'08:00',
'10:00',
'12:00',
'16:00',
'18:00',
'20:00',
'22:00',
], //X轴坐标数据
danwei: '', //y显示的刻度和单位
}
},
mounted() {
this.clickDL()
this.draw()
},
methods: {
clickDL() {
;(this.dianliuS = 'primary'), (this.dianyaS = '')
this.sanxiangS = ''
this.title = '电流'
;(this.series = [
{
name: '电流1',
type: 'line',
data: [1, 3, 9, 27, 22, 33, 33, 44, 32, 43, 21],
},
{
name: '电流2',
type: 'line',
data: [1, 2, 4, 8, 16, 32, 23, 25, 34, 27, 11],
},
{
name: '电流3',
type: 'line',
data: [3, 3, 6, 2, 10, 16, 18, 14, 22, 33, 35],
},
{
name: '电流4',
type: 'line',
data: [0, 3, 4, 12, 10, 6, 22, 16, 12, 23, 25],
},
]),
(this.danwei = { formatter: '{value} (kW)' })
this.draw()
},
clickDY() {
;(this.dianliuS = ''), (this.dianyaS = 'primary')
this.sanxiangS = ''
this.title = '电压'
// 电压数据
this.series = [
{
name: '电压1',
type: 'line',
data: [1, 3, 9, 27, 81, 247, 741, 2223, 6669],
},
{
name: '电压2',
type: 'line',
data: [1, 2, 4, 8, 16, 32, 64, 128, 256],
},
]
this.danwei = { formatter: '{value} (V)' }
this.draw()
console.log(this.series)
},
clickSx() {
;(this.dianliuS = ''), (this.dianyaS = '')
this.sanxiangS = 'primary'
this.title = '三相电流'
this.series = [
{
name: '三相电流1',
type: 'line',
data: [1, 3, 3, 3, 5],
},
{
name: '三相电流2',
type: 'line',
data: [2, 5, 6, 7, 10, 22, 33],
},
]
this.danwei = { formatter: '{value} (mA)' }
this.draw()
},
draw() {
var chartDom = document.getElementById('main')
var myChart = echarts.init(chartDom)
myChart.clear()
myChart.setOption(this.option())
// echarts表格自适应!!
setTimeout(function () {
window.onresize = function () {
myChart.resize();
};
}, 200);
},
option() {
var option = {
title: {
text: this.title,
left: 'center',
},
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b} : {c}',
},
legend: {
left: 'left',
},
xAxis: {
type: 'category',
name: '时间',
splitLine: { show: false },
data: this.xAxis,
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true,
},
yAxis: {
type: 'value',
name: '电流',
minorSplitLine: {
show: true,
},
axisLabel: this.danwei,
},
series: this.series,
}
return option
},
},
}
</script>
<style lang="scss" scoped></style>
更多推荐
所有评论(0)