由于项目中需要对数据进行可视化处理,也就是用图表表示,使大量枯燥无谓的数据变得更加直观、易于理解、可读性强,针对传统处理方式不足,数据可视化显得尤为重要,也就有了基于ECharts的数据可视化,众所周知echarts是非常强大的插件,这一期就来说一下ECharts的使用。
一、安装echarts依赖
在安装node.js之后,使用npm安装使用的是国外的地址,经常会出现超时错误,这时候可以通过修改为国内的淘宝镜像来加速安装。
npm install echarts -S
或者使用淘宝的镜像
npm install -g cnpm --registry=registry.npm.taobao.org
cnpm install echarts -S
二、创建图表
- 首先我们要全局引入
在main.js中引入
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
- 在echarts.vue页面中引入
//html 部分
<template>
<div class="home">
<div id="newCharts"></div>
</div>
</template>
//css部分
<style lang="less">
.home {
widows: 100%;
height: 100%;
#newCharts {
width: 100%;
height: 100%;
}
}
</style>
这里的echarts初始化在钩子函数mounted()中,
//js部分
export default {
name: "example",
data() {
return {
formatter: "{value}",
};
},
mounted() {
this.showCharts();
},
methods: {
showCharts() {
let myChart = this.$echarts.init(document.getElementById("newCharts"));
myChart.setOption({
title: { text: "统计" },
legend: {
data: ["天", "月", "年"],
},
tooltip: {
trigger: "axis",
axisPointer: {
type: "cross",
label: {
backgroundColor: "#6a7985",
},
},
},
xAxis: {
type: "category",
axisTick: {
alignWithLabel: true,
},
data: [
"一月", "二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",
],
nameLocation: "start",
nameTextStyle: {
align: "center",
verticalAlign: "top",
lineHeight: 28,
fontSize: 10,
color: "#ccc",
},
axisLabel: {
interval: "auto",
},
},
yAxis: {
type: "value",
axisLabel: {
formatter: this.formatter,
},
},
grid: {
left: 50,
},
series: [
{
data: [75, 95, 90, 88, 90, 126, 123, 110, 120, 145, 113, 135],
name: "天",
type: "line",
},
{
data: [50, 45, 57, 25, 55, 70, 65, 70, 68, 80, 55, 58],
type: "line",
name: "月",
},
{
data: [64, 70, 70, 75, 63, 60, 70, 78, 108, 100, 110, 108],
type: "line",
name: "年",
},
],
});
},
},
};
</script>
当我们写完以后 在运行的时候就会报一个错,如下图,这是什么原因呢?先别急
解决方法:
//在import后面,echarts前面加*as
import * as echarts from 'echarts'
Vue.prototype.$echarts = echarts;
改完之后再次运行,结果如下
这样一个简单的折线图就出来了 在这里要提醒一下大家,上面全局引入会将所有的echarts图标打包,导致体积过大,所以我觉得最好还是按需引入比较好。
3.按需引入
在main.js中引入
//引入 ECharts 主模块
let echarts = require('echarts/lib/echarts');
//按需引入echart折线图等组件
require('echarts/lib/chart/line');
// 引入提示框和title组件
require('echarts/lib/component/tooltip');
require('echarts/lib/component/title');
require('echarts/lib/component/grid');
//vue全局注入echarts
Vue.prototype.$echarts = echarts;
这里之所以使用 require 而不是 import,是因为 require 可以直接从 node_modules 中查找,而 import 必须把路径写全。
完美收工如果这篇掘金对你有所帮助的话,请点个赞吧,感谢各位看官的支持啦!