一、安装
npm install echarts --save
二、引入和使用
import * as echarts from 'echarts'
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'))
// 绘制图表
myChart.setOption({
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
})
三、封装成Echarts组件使用
当在项目中多个地方用到Echarts图表时,封装成组件使用会更为简便。
1、创建Echarts组件 "@/components/Echarts/index.vue"
<template>
<div :id="id" :style="{ width: width ? `${width}px` : '', height: height ? `${height}px` : '' }" class="my-echarts"></div>
</template>
<script>
import * as echarts from 'echarts'
export default {
name: 'Echarts',
data () {
return {
id: '',
chart: ''
}
},
props: {
option: {
type: Object,
default: () => {
return {
title: {
text: 'ECharts 示例'
},
tooltip: {},
legend: {},
xAxis: {
type: 'category',
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {
type: 'value'
},
series: [{
name: '销量',
data: [820, 932, 901, 934, 1290, 1330],
type: 'line'
}]
}
}
},
width: {
type: [String, Number],
default: ''
},
height: {
type: [String, Number],
default: ''
}
},
watch: {
option: {
handler (newVal, oldVal) {
if (this.chart) {
this.chart.setOption(newVal)
} else {
this.init()
}
},
deep: true
}
},
created () {
// 设置随机数id
let t = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
let len = t.length
let id = ''
for (let i = 0; i < 32; i++) {
id += t.charAt(Math.floor(Math.random() * len))
}
this.id = id
},
mounted () {
this.init()
},
methods: {
init () {
this.chart = echarts.init(document.getElementById(this.id))
this.chart.setOption(this.option)
window.addEventListener('resize', this.chart.resize)
}
}
}
</script>
<style lang="scss" scoped>
.my-echarts {
width: 100%;
height: 100%;
}
</style>
2、引入组件并使用
<template>
<div class="echarts-box">
<Echarts :option="option" :width="380" :height="380"></Echarts>
</div>
</template>
<script>
import Echarts from '@/components/Echarts/index.vue'
export default {
name: 'Index',
components: {
Echarts
},
data () {
return {
option: {}
}
},
created () {
this.initEcharts()
},
methods: {
initEcharts () {
const total = 20
this.option = {
tooltip: {
trigger: 'item',
// 是否将 tooltip 框限制在图表的区域内
confine: true
},
legend: {
show: false
},
graphic: [
{ // 环形图中间添加文字
type: 'text', // 通过不同top值可以设置上下显示
left: 'center',
top: '45%',
style: {
text: '累计',
textAlign: 'center',
fill: '#666666', // 文字的颜色
fontSize: 14
}
},
{ // 环形图中间添加文字
type: 'text', // 通过不同top值可以设置上下显示
left: 'center',
top: '56%',
style: {
text: `${total} 件`,
textAlign: 'center',
fill: '#666666', // 文字的颜色
fontSize: 16
}
}
],
color: ['#6295F8', '#61DAAB', '#FF990B'],
series: [
{
type: 'pie',
radius: ['45%', '75%'],
data: [{ name: '在办', value: 14 }, { name: '归档', value: 6 }],
label: {
show: true,
// width: 100,
formatter: '{b}:{c} ({d}%)',
overflow: 'break'
},
labelLine: {
length: 0
}
}
]
}
}
}
}
</script>
<style lang="scss" scoped>
</style>
3、实现效果
记录于2022-10-18.