开局一张图
实现比较简单,主要是遍历时动态绑定ref
,然后再遍历数据渲染就OK了
下面是全部代码
<template>
<div>
<div class="chart-wrap">
<!-- 动态设置ref -->
<div v-for="(item, index) in data" :key="index" class="chart" :ref="`chart_${index}`"></div>
</div>
</div>
</template>
<script>
import * as echarts from 'echarts'
export default {
name: 'echarts',
data () {
return {
data: [[
{ value: 1048, name: '语文' },
{ value: 735, name: '数学' },
{ value: 580, name: '英语' },
{ value: 484, name: '物理' },
{ value: 300, name: '化学' }
], [
{ value: 654, name: '语文' },
{ value: 456, name: '数学' },
{ value: 674, name: '英语' },
{ value: 563, name: '物理' },
{ value: 456, name: '化学' }
], [
{ value: 567, name: '语文' },
{ value: 765, name: '数学' },
{ value: 657, name: '英语' },
{ value: 456, name: '物理' },
{ value: 876, name: '化学' }
]],
chartArr: []
}
},
mounted () {
this.data.forEach((item, index) => {
const chart = echarts.init(this.$refs[`chart_${index}`][0])
// 将实例保存到chartArr中,用于联动,如果不需要联动,这里就不需要了
this.chartArr.push(chart)
chart.setOption({
tooltip: {
trigger: 'item'
},
series: [
{
name: 'pie',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
label: {
show: true,
position: 'inside'
},
data: item
}
]
})
})
// 图表实例实现联动
echarts.connect(this.chartArr)
}
}
</script>
<style lang="scss" scoped>
.chart-wrap {
width: 1020px;
margin: 0 auto;
display: flex;
}
.chart {
width: 33.3333%;
height: 300px;
}
</style>