在Vue项目中引入Echarts图表
- 安装echarts插件
npm install echarts --save
在package.json中可以找到如下,即安装成功:
"dependencies": {
"echarts": "^4.8.0",
},
2.在main.js中引入
import Echarts from 'echarts' // 引入Echarts插件
// 注册Echarts插件
Vue.prototype.$echarts = Echarts
3.在Home.vue文件中的<script></script>
标签内引入:
let Echarts = require('echarts/lib/echarts')
// 按需引入对应的模块
require('echarts/lib/chart/bar')
4.在<template></template>
中定义防止chart的容器,此容易一定要定义宽高:id和ref二选一即可
<div id="chart-one" ref="chart"></div>
5.在Home.vue中继续完成以下代码,即可实现柱形图表:
data() {
return {
chart: null
}
},
// 挂在Echarts实例的dom节点
mounted () {
// 调用方法绘制图表
this.initChart()
// 自适应窗口大小
window.addEventListener('resize', () => {
this.chart.resize()
})
},
methods: {
initChart () {
// 初始化Echarts实例
// 使用id的方式绑定容器时使用
this.chart = Echarts.init(document.getElementById('chart-one'))
// 使用ref绑定图表放置的容器时使用
// this.chart = Echarts.init(this.$refs.chart)
// 绘制图表
let option = {
title: {
text: '3M中国有限公司'
},
tooltip: {},
legend: {
data: ['日销量/(w)']
},
xAxis: {
data: ['印度', '美国', '日本', '越南', '中国', '韩国']
},
yAxis: {},
series: [{
name: '日销量/(w)',
type: 'bar',
data: [50, 20, 36, 10, 10, 20]
}]
}
this.chart.setOption(option)
}
}
6.补充:
series: 决定图表类型的;
clockWise:饼图的扇区是否是顺时针排布。
radius: 设置环形饼状图, 第一个百分数设置内圈大小,第二个百分数设置外圈大小。
itemStyle: 设置饼状图扇形区域样式
hoverAnimation: 鼠标放上去是否有动画效果
center: 设置饼状图位置,第一个百分数调水平位置,第二个百分数调垂直位置。
data:
formatter: 饼图里中间的文字
position: 文字位置
textStyle: 文字样式设置
color: 设置饼图里渐变色的